繁体   English   中英

如何基于另一个表中值的数量从表中获取记录

[英]How to get records from a table based on the quantity of a value in an other table

所以我有表A(城市)

身份证,城市,国家

和表B(行程)

id,旅行,城市,活跃

我想选择所有使用MySQL的城市,但要按活跃度为1时它们在表B中显示的次数进行排序。

提前致谢

您可以尝试两个查询并比较效果

select a.city, count(*) as cnt
from cities as a
left join
trips as b
on (a.id = b.city and b.active=1)
group by a.city
order by 2 desc

要么

select
    a.city,
    (select count(*) from trips as b where a.id = b.city and b.active=1) as cnt
from cities as a
order by 2 desc

然后将联接B保留在A并在联接子句中包含active = 1条件,并按城市分组。

select a.city, count(b.city) as cnt
from a
left join b on a.id=b.city and b.active=1
group by a.id, a.city
order by count(b.city) desc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM