What is wrong with this MySQL Query? need help to understand
I have 4 tables namely,
countries, states, cities, areas,
apart from countries table the rest three(states,cities,areas) contains country_id foreign key.
i wanted to return the total number of count of country_id combined in three tables for which i used jon_darstar's solution, here is the code i am using.
SELECT COUNT(DISTINCT(states.id)) + COUNT(DISTINCT(cities.id)) + COUNT(DISTINCT(areas.id))
FROM states
JOIN cities on cities.country_id = states.country_id
JOIN areas on areas.country_id = states.country_id
WHERE states.country_id IN (118);
the above code works perfectly fine although i am unable to understand the code properly, mainly the first line i.e
SELECT COUNT(DISTINCT(states.id)) + COUNT(DISTINCT(cities.id)) + COUNT(DISTINCT(areas.id))
Question 1 : doesn't that select the primary 开发者_Go百科id of the three tables states,cities and areas and make the count? i know this is not happening from the result i am getting then what is actually happening here?
However if i remove the DISTINCT from the query string it shows me a different result i.e a count of 120 whereas actually it should be 15(this is the count number of country_id in all three tables).
Question 2 : What is happening if i use DISTINCT and remove DISTINCT? isn't DISTINCT supposed to remove any duplicate values. where is duplication happening here?
thank you..
For an example, if in a country A(having primary id a.id=118),there is State B(having primary id b.id),inside that state there is City C(having primary id c.id), In city C there's Area D(having primary id d.id),E(having primary id e.id),F(f.id).lets visualize the query result in a database table.
C St Ct Ar
A->B->C->D
A->B->C->E
A->B->C->F
(Here C=Country,St=States,Ct=Cities,Ar=Areas)
Now just think what happens when you do count on above table to get total number of States within Country A without distinct.The result is 3,this way the Number of Cities is 3 and areas is 3,total 9.Because without distinct you're getting duplicate values in which you're not interested.
Now,if you use distinct count you'll get correct result cause here distinct states under country A is 1,City is 1 and Areas is 3,total:5(excluding duplicate values)..
Hope this works!
!!Design Issue!!!
Like to add something:From your database design,i can see that you're using country id as a reference for countries from country table(to states,areas and cities) then joining states and cities then states and areas (by their country id)don't you think it's creating cross join?.Better design choice is at areas table keep foreign key of city,this way go bottom up like in city keep states and in states keep country.Or make a table for Areas where you are keeping Countries,States,Cities foreign key and areas primary key.
精彩评论