首页 > 解决方案 > 如何在左连接表中执行自连接?

问题描述

我有两张桌子

第一个是“博客”表:

+----+--------+--------+
| 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         |
+----+---------+--------+------------+--------------------+

标签: sql

解决方案


我想我会使用existsand 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).


推荐阅读