gpt4 book ai didi

mysql - 连接表并返回每条记录的匹配总数

转载 作者:行者123 更新时间:2023-11-29 08:07:26 25 4
gpt4 key购买 nike

我有以下两个表:

行动:

id | action
---|--------
1 | Some action
2 | Another action
3 | And another

和已完成的操作:

id | userid | actionid
---|--------|---------
1 | 4 | 1
2 | 4 | 2
3 | 4 | 2
4 | 4 | 2
5 | 5 | 1

并希望将它们加入到给定的用户 ID 上,然后返回所有操作以及用户完成操作的次数,返回一个表,如下以 userid=4 为例:

id | action         | times
---|----------------|-------
1 | Some action | 1
2 | Another Action | 3
3 | And Another | 0

这在 MySQL 中可能吗?

最佳答案

这是一个基本的连接/聚合查询,略有不同:

select a.id, a.action, count(ca.userid) as times
from Actions a left outer join
CompletedActions ca
on ca.actionid = a.id and
ca.userid = 4
group by a.actionid;

略有不同的是使用左外连接来确保所有操作都包含在结果中。

顺便说一句,您还可以使用相关子查询来编写此内容:

select a.*,
(select count(*)
from CompletedActions ca
where ca.actionid = a.id and
ca.userid = 4
) as times
from actions a;

在某些情况下,这可以获得更好的性能。

关于mysql - 连接表并返回每条记录的匹配总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425305/

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