vendredi 30 janvier 2015

Use join to aggregate data from various normalized tables


I have a database as follows:



tbl_clients (Primary Key: client_id, Foreign Keys:place_id,district_id,zone_id,country_id)
tbl_places (Primary Key: place_id)
tbl_districts (Primary key: district_id)
tbl_zones (Primary Key: zone_id)
tbl_country (Primary key: country_id)
tbl_branches (primary key: branch_id, Foreign Key: client_id)


My client asked me to provide all the data in a csv file. The requirement is:


If a client has branches, the branches details also should show.(from tbl_branch) If a client does not have branches,only its details should show.


I have achieved the second condition using the following:


select distinct



a.name as Client_Name,
a.pobox_no as Postal_Address,
a.street as Street_Address,
d.place_name as Place,
e.district_name as District,
f.zone_name as Zone,
g.country_name as Country,
a.fax as Fax,
a.telephone as Telephone,
a.telephone2 as Telephone2,
a.email as Email,
a.website as website,
a.published as Published


from db_name.tbl_client a


join



db_name.tbl_subcategory b on a.sub_cat_id = b.cat_id


join



db_name.tbl_category c on a.category_id = c.id


join



db_name.tbl_place d on a.place_id = d.place_id


join



db_name.tbl_districts e on a.district_id = e.district_id


join



db_name.tbl_zones f on a.zone_id = f.zone_id


join



db_name.tbl_country g on a.country_id = g.country_id


where a.published = 1


How can I achieve the first condition?





Aucun commentaire:

Enregistrer un commentaire