1

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

状态:

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

4 回答 4

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';
于 2012-04-18T19:42:26.377 回答
0

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

于 2012-04-18T19:42:22.947 回答
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'
于 2012-04-18T19:44:56.667 回答
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 "
于 2012-04-18T19:45:06.853 回答