mysql同时查询三张表的问题

FVG55 2015-07-12 12:29:33
数据表
users有字段uid,b,c
orders有字段oid,uid,e
products有字段pid,uid

现在要将users所有查询出来,并且统计每个users的uid在orders表中的个数和products中的个数,我这样写的
select users.uid,count(orders.uid),count(products.uid) from users,orders,products where users.uid=orders.uid and users.uid=products.uid
可是这样查询的话,如果users用户在orders或products没有记录的话,这个users就没被查询出来,我的目的是就算没有记录,也要查询出来,显示0即可。请问要怎么改?
...全文
322 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ACMAIN_CHM 2015-07-13
  • 打赏
  • 举报
回复
这个不能使用JOIN查询,会造成重复。
select uid,
	(select count(*) from orders where uid=users.uid),
	(select count(*) from products where uid=users.uid)
from users
道玄希言 2015-07-12
  • 打赏
  • 举报
回复


select  T1.uid, ifnull(T2.uid, 0),  ifnull(T3.uid, 0) 
from  users as T1
left join (select count(uid) as uid from orders group by uid) as T2
on T1.uid =T2.uid
left join ((select count(uid) as uid from products group by uid) as T3
on T1.uid =T3.uid

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧