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

标签 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'";

最佳答案

使用这个查询:

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

关于php - MySQL/PHP 从多个表中选择和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10216729/

相关文章:

MySQL linux 服务器和 my.cnf 优化多行

没有存储例程的MySQL循环

php - 获取匹配记录数

php - mysql, php, 如何比较数字

nginx - PHP 语法错误,意外 '['

php - 用于高效搜索用户名的 SQL

sql - 如何排除匹配连接在 SQL 树中的行

MySQL:每月计算一次条目,直到条目发生变化

php - MySQL 错误 "Expression #1 of ORDER BY clause is not in GROUP BY clause"

php - 如何在 Laravel 中获取平均时间