[英]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.