Let’s say I have 3 tables:
Table 1 called “states”:
id | state
1 italy
2 netherlands
3 russia
Table 2 called “hotels”:
id | hotel name | belongsToCountry
1 Green Hotel 2
2 Luxurious 2
3 Get Warm! 3
Table 3 called “free rooms”:
id | roomID | belongsToHotel
1 815 2
2 912 2
3 145 1
4 512 1
5 1200 3
Now, what I need to echo is this:
Netherlands has 4 free rooms.
Russia has 1 free room.
In words:
I need to make a list of all states which have at least 1 free room and I need to return the exact value of how many free rooms there are.
If anyone can help me with this, I’d be so grateful!
Let’s build the query step by step.
First, let’s assemble the list of hotels and their free room count.
INNER JOINs force rows from the table on the “left” side of the join (hotels) only to be included in the result set when there is a corresponding table on the “right” (free_rooms). I’m assuming here that there will only be a row infree_roomswhen the room is free.Having this, we can now join against the list-o-nations.
It should be noted, by the way, that you’ve made poor choices in naming these columns.
statesshould be composed ofidandstate_name,hotelsshould beid,hotel_name,state_id, andfree_roomsshould beid,room_nameandhotel_id. (I could also argue thatstates.idshould bestates.state_id,hotels.idshould behotels.hotel_idandfree_rooms.idshould befree_rooms.room_idbecause that makes the joins much easier…)If you need to represent a “belongs to” relationship, you’re actually looking for foreign key restraints. You should use those instead of special naming.
*ahem* Where was I? Oh yes. The second query will result in a result set with three columns – the hotel id, the number of rooms in it, and the country it’s in. But, you just need the number of rooms per country, so let’s do one last change.
Only two changes. First, we’re now grouping together by state. Second, we’re no longer including the hotel id in the result set. This should get you the data you need, again assuming that there will never be a row in
free_roomswhen the room is not free.