MySQL 5.6父级/子级-如果给出ID,则返回最新(最小的子级)记录

时间:2019-03-21 06:25:15

标签: mysql

MySQL 5.6

给出以下模式:

    |id|product_id|parent_id|ordered|sent|BO  |date_updated       |
    ---------------------------------------------------------------
    |1 |12313     |NULL     |2      |NULL|NULL|2019-03-01 13:24:00|
    ---------------------------------------------------------------
    |2 |12313     |1        |2      |1   |1   |2019-03-02 10:24:00|
    ---------------------------------------------------------------
    |3 |12313     |2        |2      |2   |0   |2019-03-04 16:40:00|
    ---------------------------------------------------------------

如果给我一个特定的ID(即2),我该如何编写sql查询来为我提供关系中的最新记录(即3)?

此外,如果给我id 1,我也需要返回最新的(id 3)记录。关系级别未知。它可以有n个孩子。

如果给我id为3,我需要返回id 3(因为它是最新记录)。

1 个答案:

答案 0 :(得分:1)

对于要在MySQL 5.7或更早版本上运行的查询,我将使用以下代码:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT product_id, MAX(date_updated) AS max_date_updated
    FROM yourTable
    WHERE product_id = (SELECT product_id FROM yourTable
                        WHERE id = 1)  -- replace with your id value
    GROUP BY product_id
) t2
    ON t1.product_id = t2.product_id AND
       t1.date_updated = t2.max_date_updated;

如@PaulSpiegel所述,我们还可以在此处使用LIMIT子查询技巧:

SELECT *
FROM yourTable
WHERE product_id = (SELECT product_id FROM yourTable WHERE id = 1)
ORDER BY date_updated DESC
LIMIT 1;