在LEFT JOIN语句中将一列的结果设置为另一列的值

时间:2019-01-10 19:07:02

标签: mysql sql

我要连接来自同一表的两个相关的行,基本上是“根行”和最新的更新行。我希望有一种方法可以将根列行的值设置为最新更新中的一行。仅在返回的结果中,我不想更新最新列的数据库行。

/* Table Name:  posts */
+--------+---------+-------------+--------------+
|   ID   |   ROOT  |   PUBLISHED |   DELETED    |
+--------+---------+-------------+--------------+
|   01   |     01  |    FALSE    |     NULL     |
+--------+---------+-------------+--------------+
|   02   |     01  |     NULL    |  01/03/2019  |
+--------+---------+-------------+--------------+
|   03   |     01  |     NULL    |  01/04/2019  |
+--------+---------+-------------+--------------+
|   04   |     01  |     NULL    |     NULL     |
+--------+---------+-------------+--------------+

我要执行的查询选择第04行,因为它是最新的,并且我尝试加入根行(01),然后使行04的值在返回结果中具有“ FALSE”,同时在数据库中保留“ NULL”。

SELECT p1.*, p2.ID, p2.PUBLISHED
FROM posts p1
LEFT JOIN posts p2 ON p1.ID = p2.ID
WHERE p1.DELETED = NULL

我尝试了一些事情并且一直在环顾四周,但是我一直被卡住。

SELECT p1.*, p2.ID, p2.PUBLISHED, p1.PUBLISHED = p2.PUBLISHED
FROM posts p1
LEFT JOIN posts p2 ON p1.ID = p2.ID
WHERE p1.DELETED = NULL

SELECT p1.*, p2.ID, p2.PUBLISHED, p1.PUBLISHED as p2.PUBLISHED
FROM posts p1
LEFT JOIN posts p2 ON p1.ID = p2.ID
WHERE p1.DELETED = NULL

谢谢阅读这篇文章的人

1 个答案:

答案 0 :(得分:1)

您可以加入子查询以获取最大的未删除ID。然后也进行自我连接以获取根。

SELECT p1.id,
       p1.root,
       p4.published,
       p1.deleted
       FROM posts p1
            INNER JOIN (SELECT max(p2.id) id
                               FROM posts p2
                               WHERE p2.deleted IS NULL) p3
                       ON p3.id = p1.id
            INNER JOIN posts p4
                       ON p4.id = p1.root;