MySQL / PHP从多个表中选择和计数

时间:2012-04-18 19:38:36

标签: php mysql

我甚至不确定这是可能的......我会告诉你我正在做什么,然后我想做什么:

状态:

state_id

town_id
state_id
misc_property

街景:

street_id
town_id
state_id

这些是在层次结构中设置的。

我想选择的内容:

我想选择所有具有misc_property的城镇,同时选择它所属的州并计算该镇的所有街道。

这是我到目前为止所做的:

$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 个答案:

答案 0 :(得分:2)

使用此查询:

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';

答案 1 :(得分:0)

您可以将GROUP BY town_id与HAVING一起用于特殊的WHERE条件

答案 2 :(得分:0)

使用联接:

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'

答案 3 :(得分:0)

你可以这样做

$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 "