sql - 如何在左连接表中执行自连接?
问题描述
我有两张桌子
第一个是“博客”表:
+----+--------+--------+
| id | title | status |
+----+--------+--------+
| 1 | blog 1 | 1 |
| 2 | blog 2 | 1 |
+----+--------+--------+
其次是 blog_activity:
状态1是:创建状态2是:打开
+----+---------+--------+------------+
| id | blog_id | status | date |
+----+---------+--------+------------+
| 1 | 1 | 1 | 2019-09-09 |
| 2 | 2 | 1 | 2019-09-10 |
| 2 | 2 | 2 | 2019-09-11 |
+----+---------+--------+------------+
我希望博客记录没有打开博客表的所有详细信息。
例子 :
+----+---------+--------+------------+--------------------+
| id | blog_id | title | blog.date | blog_activity.date |
+----+---------+--------+------------+--------------------+
| 1 | 1 | blog 1 | 2019-09-09 | 2019-09-09 |
+----+---------+--------+------------+--------------------+
解决方案
我想我会使用exists
and join
:
select b.*, ba.date as created_date
from blog b join
blog_activity ba
on ba.blog_id = b.id and ba.status = 1
where not exists (select 1
from block_activity ba2
where ba2.blog_id = b.id and ba2.status = 2
);
这避免了聚合,它可以在blog_activity(blog_id, status)
.
推荐阅读
- mongodb - MongoDB 部分索引无法按预期使用计数
- javascript - React 从导入中消除点
- android - 如何让浓缩咖啡等待由firebase调用触发的活动?
- database - 将 pymysql 与 pycharm 一起使用
- java - testng范围报告中测试和步骤之间的区别
- android - 在 Recyclerview 值中的 radiogroup 中获取单选按钮关联的 ArrayList 值
- java - 如何在线性布局中访问膨胀视图
- c++ - 如何包含 uniform_real_distribution 的最大值
- ios - UIImageView 不会改变大小
- excel - 根据行号将单元格从 Sheet1 中的 B:D 列复制到 Sheet2 中的 C:E