首页 > 解决方案 > MySQL比较行数以查看哪个用户在另一个表中有一行

问题描述

我正在建立一个调查系统

客户端 A 可能有用户 [1,2,3]。现在有一个表user_completions,它显示了哪些用户完成了我的调查。

users table
+----+-----------+
| id | client_id |
+----+-----------+
|  1 |         1 |
|  2 |         1 |
+----+-----------+


user_completions table
+---------+-----------+
| user_id | survey_id |
+---------+-----------+
|       1 |         1 |
|       2 |         2 |
+---------+-----------+

我如何(在一个查询中)查看有多少用户在 user_completion 表中有记录,按调查分组,并且仅适用于当前客户

期望的结果看起来像

+-----------+-------+-----------------------+
| survey_id | users | num_persons_completed |
+-----------+-------+-----------------------+
|         1 |     2 |         1             |
|         2 |     2 |         1             |
+-----------+-------+-----------------------+

标签: phpmysqllaravel

解决方案


我认为您在问题中遗漏了几个表,但如果您真的只有这两个表,那么您可以通过以下查询来实现这一点:

select tmp.survey_id, count(distinct tmp.user_id) completed, 
      (select count(distinct id) from users where client_id = 1) users
from
(select t1.*, t2.*
from users t1 
join user_completions t2
on t1.id = t2.user_id
where t1.client_id = 1
)tmp
group by tmp.survey_id

推荐阅读