gpt4 book ai didi

mysql - 加入查询也返回空

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:04 24 4
gpt4 key购买 nike

我有三个表(更多列但列出了重要的):

users
user_id - name
1 DAN
2 TED
3 SAM

list_shares
list_shares_id - user_id - list_id
1 1 123
2 3 123
3 2 456

list_contribute
list_contr_id - list_id - can_contribute
1 123 3

我想显示 list_id 下表 list_shares 中的所有用户,将其与 users 表连接以获取用户信息,并计算其中有多少人也在 contribution 表中

基本上 - 用户可以与其他用户共享列表,也可以邀请一些用户做出贡献,但并非所有共享的用户都可以贡献,因此需要单独的 list_contribute 表。

这是我首先使用的,它只显示具有特定 ID 的所有用户:

select u.name, u.live_prof_pic, u.url, u.user_id from list_shares ls 
join users u on ls.user_id = u.user_id
where ls.list_id = '123'

这带来了两个结果,这是正确的——下一个查询试图找出这两个中的哪一个也在 list_contribute 表中——但是,它将结果减少为一个,而我希望它返回两个并显示 0 how_many 如果不在 list_contribute 中

select u.name, u.live_prof_pic, u.url, count(ls.list_shares_id) as how_many, u.user_id from list_shares ls
join users u on ls.user_id = u.user_id
left join list_contribute lc on ls.list_id = lc.list_id
where ls.list_id = '123'

在上面的数据中我要返回

user_id    name    how_many    
3 SAM 1
1 DAN 0

最佳答案

添加一个 GROUP BY 使其成为标准的 SQL 聚合

select u.name, u.live_prof_pic, u.url, count(ls.list_shares_id) as how_many, u.user_id
from
list_shares ls
join users u on ls.user_id = u.user_id
left join list_contribute lc on ls.event_id = lc.event_id
where ls.list_id = '123'
group by u.name, u.live_prof_pic, u.url, u.user_id

MySQL 有一个 rubbish试图删除要求但经常提供不正确数据的扩展

评论后编辑。

您仍然应该使用正确的 GROUP BY 语法

但是,您的 COUNT 应该是 COUNT(lc.event_id) 以计算子行。

关于mysql - 加入查询也返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13087836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com