1

I'm not even sure this is possible... I'll show you what I'm working with, then what I would like to do:

state:

state_id

town:

town_id
state_id
misc_property

street:

street_id
town_id
state_id

These are set up in a hierarchy.

What I want to select:

I would like to select all towns with a misc_property, while at the same time selected the state it belongs to and counting all of the streets in that town.

This is what I have so far:

$sql="SELECT 
    a.state_id AS state_id, 
    b.town_id AS town_id, 
    COUNT(c.street_id) 

    FROM 
    state a, 
    town b, 
    street c 

    WHERE 
    b.misc_property='$property'";

4 Answers 4

2

Use this query:

SELECT
    town.state_id AS state_id,
    town.town_id AS town_id,
    COUNT(street.street_id) AS count
FROM
    state INNER JOIN town ON state.state_id = town.state_id 
    LEFT JOIN street ON town.town_id = street.town_id
GROUP BY
    state_id,
    town_id
HAVING
    town.misc_property = 'stuff';
Sign up to request clarification or add additional context in comments.

4 Comments

good solution, bt should'nt JOIN be LEFT join rather than INNER join? because there may exist a town without street entry. (ofcourse its more of business logic). but am just commenting in the current question's context. cheers..!
What if I needed to grab something from the state besides the id?
I added the state to the joins. You can now put columns from the state table in the select section.
Thank you. I removed state_id in the GROUP BY. Not sure why that was needed. For some reason in the HAVING clause town.misc_property was not accepted until i put in the SELECT clause town.misc_property AS misc_property. if you have any thoughts, it would be appreciated.
0

you can use GROUP BY town_id with HAVING for special WHERE conditions

Comments

0

Use joins:

SELECT * FROM state
LEFT JOIN town ON state.state_id = town.state_id
LEFT JOIN street ON street.town_id = town.town_id
WHERE town.misc_property = '$property'

2 Comments

You're not counting the streets.
You are right, I missed that. Yup, your query seems to be the best way to do this.
0

you can do like this

$sql="SELECT 
    a.state_id AS state_id, 
    b.town_id AS town_id, 
    Select COUNT(c.street_id) From C Where C.town_id = b.town_id 

    FROM 
    state a, 
    town b, 
    street c 

    WHERE 
    b.misc_property='$property'and b.state_id = a.state_id "

2 Comments

You should join the tables, not subquery them.
yeah join is better but just to make it simple on edit his code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.