mysql - 根据特定条件加入 3 个表
问题描述
我有以下 3 个表:
- 用户:[id, name, admin ...]
- 事件:[id, user_id, type ...]
- 消息:[id, user_id, ...]
我想构建一个执行以下操作的查询:
-> 从表用户中选择所有未安排“集合”类型事件的用户
-> 并且谁拥有少于 3条“collection_reminder” 类型的消息
-> 谁不是管理员
我已经设法弄清楚了这个查询的第一部分,但是当我尝试添加 3 个表、进行计数等时,这一切都变得有点梨形了。
解决方案
This query uses joins to link the 3 tables, filters the result using the where clause, and using Group by, having limiting the result to only those who satisfy the less than count condition..
SELECT a.id,
SUM(CASE WHEN b.type = 'collection' THEN 1 ELSE 0 END),
SUM(CASE WHEN c.type = 'collection_reminder' THEN 1 ELSE 0 END
FROM users a
left join events b on (b.user_id = a.id)
left join messages c on (c.user_id = a.id)
WHERE a.admin = false
GROUP BY a.id
HAVING SUM(CASE WHEN b.type = 'collection' THEN 1 ELSE 0 END) = 0
AND SUM(CASE WHEN c.type = 'collection_reminder' THEN 1 ELSE 0 END) < 3
推荐阅读
- go - 在 Go 中生成构建时间戳
- php - 用php和sql建表
- javascript - 将字符串(Revit 公式)转换为 JavaScript 对象
- google-play - 我的应用程序从 Play 商店中消失了......即使它仍然在开发者控制台中发布
- facebook - 如何撤销特定的 Facebook 访问令牌
- asp.net-mvc - 无法在 Angular 6 组件 templateurl 下加载 MVC 部分视图
- python - 更新未在 pygame 中注册的矩形坐标?
- php - 如何从图像元数据 php 中获取标签?
- android - 通过 Google 街景获取沿途图像?
- java - 是否可以清除java控制台?