views:

30

answers:

0

Hello ALL,

I have following table structure

table_country ==> country_id (PK) | country | status
table_department ==> department_id (PK) | department | country_id (FK)
table_province ==> province_id (PK) | province | department_id (FK)
table_district ==> district_id (PK) | district | province_id (FK)

NOTE: all tables engine  are innoDB

One country can have multiple department, one department can have multiple provine and one province can have multiple district. Now i need to search only those country which have atleast one district

i write below 2 SQL quries, in my case, both query give same results....please describe me the difference between below queries and suggest me to use optimized query

USING RIGHT JOIN

SELECT c.country_id as id, c.country as name 
FROM table_country c 
RIGHT JOIN table_department d ON d.country_id=c.country_id 
RIGHT JOIN  table_province p ON p.department_id=d.department_id 
RIGHT JOIN table_district ds ON ds.province_id=p.province_id 
WHERE   c.status='Active' GROUP BY (c.country_id)

USING INNER JOIN and HAVING Clause

SELECT COUNT(ds.district),c.country_id as id, c.country as name 
FROM table_country c 
INNER JOIN table_department d ON d.country_id=c.country_id 
INNER JOIN table_province p ON p.department_id=d.department_id 
INNER JOIN table_district ds ON ds.province_id=p.province_id 
WHERE c.status='Active' GROUP BY (c.country_id)  
HAVING  COUNT(ds.district)>0

please tell me where these both query make the difference in results and which one i have to use or i have to use different query.

Thanks in Advance