MySQL-mysql 通过一张表的字段统计另一张表的数量 查询速度过慢,有什么办法优化吗?
有表open_city和buyerUser
open_city结构有city_id和city_name
buyerUser有city_id且可重复有多个
现在需要统计buyerUser中的city_id有多少个数量,写了sql以后发现查询速度太慢,有什么方法可以优化吗?
下面是sql语句:
select DISTINCT city_name as city,
(select count(*) from buyerUser where buyerUser.city_id=open_city.city_id and buyerUser.ISVerify='1' and Ub_state=1)
from open_city;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
子查询可以先直接统计出city_id,然后再去city表中查city_name,子查询如下:
select b.city_id, count(*) as count_ from buyerUser b where b.ISVerify='1' and b.Ub_state=1 group by b.city_id
select open_city.city_name as city,count(*)
from open_city left join buyerUser on buyerUser.city_id=open_city.city_id
where buyerUser.city_id=open_city.city_id and buyerUser.ISVerify='1' and Ub_state=1
group by open_city.city_name;
能否把表数据给出来?
这样更直观一些;
分开查询,分两次查询!!