通过连接两个表创建自定义列

时间:2014-04-07 01:44:51

标签: mysql

如果这是我需要做的,我对子查询很糟糕。首先让我向您展示我的表格的预览以及我想要做的事情。

enter image description here

这是我最后想要的结果:

business.name
reviews_count (total count, matching the current queries business_id)
where the b.industry_id matches 7

这就是我正在尝试但我感到困惑,不知道如何匹配总数,让我解释一下:

select
b.name,
reviews_count as (select count(*) as count from reviews where business_id = b.business_id),
from business as b
left join reviews as r
on r.business_id = b.id
where b.industry_id = 7

子查询business_id需要匹配正在运行的当前业务ID。希望我有道理。 (reviews_count不存在,我只是在输出时使用它)

1 个答案:

答案 0 :(得分:0)

这看起来像是GROUP BY

的工作
SELECT 
    b.name,
    count(distinct r.id)
FROM
    businesses b
    JOIN reviews r ON r.business_id = b.id
WHERE b.industry_id = 7
GROUP BY b.id

这样你就可以完全避免使用子查询。