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

标签 mysql

我有以下两个表:

行动:

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/

相关文章:

mysql - 检索每组中的最后一条记录 - MySQL

mysql - 获取分组依据的最新记录

mysql - 优化包含 EXISTS 的 MySQL UPDATE 查询的性能

php - mysql INSERT 没有做任何事情

php - 如何在wordpress中连接多个表获取数据

python - 在 python 类之间共享 python MySQL 连接对象

mysql - 在 groupby 中获取 count() 的总和

MySQL使用Select触发IF语句

sql - 选择一个字段的计数大于一的位置

c# - MySqlCommand Command.Parameters.Add 已过时