php - 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 |
+-----------+-------+-----------------------+
解决方案
我认为您在问题中遗漏了几个表,但如果您真的只有这两个表,那么您可以通过以下查询来实现这一点:
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
推荐阅读
- android - 在android中保持服务在后台运行
- javascript - 如何在 Angular 4 中管理组件之间的列表
- javascript - 如何将 JSON 对象从 R/Shiny 发送到 Cytoscape.js?
- python - TensorFlow 中实际输出之前的额外“b”
- php - ImageMagick PHP - 扭曲文本并在图像上添加注释
- jts - 如何检测lineString的异常点
- java - 聊天记录 - 图像在文本之前加载 - android
- matlab - matlab 全局文档文件夹路径
- python-3.x - 如何从 kinto.ini 文件中读取不同的块设置
- c# - 反序列化后 JSON 不保留值