如何从第二个表返回最后匹配结果的联接表?

时间:2018-08-17 19:20:00

标签: mysql

TableOne摘录:

┌─product─────┬────────────sequence─┬─qty─┐
│ A18         │ 1534334750278856541 │   7 │
└─────────────┴─────────────────────┴─────┘

TableTwo摘录:

┌────────────sequence─┬─product─────┬─size─┐
│ 1534331161780089544 │ A18         │    3 │
│ 1534333381672627454 │ A18         │    3 │
│ 1534334750278856540 │ A18         │    3 │
│ 1534334750278856540 │ A18         │    7 │
│ 1534334750278856540 │ A18         │    5 │
└─────────────────────┴─────────────┴──────┘

对于TableOne的每一行,我想在TableTwo中找到具有相同产品名称和TableTwo.sequence <= TableOne.sequence

的最后一行。

因此,鉴于上述示例数据,返回结果应如下:

TableOne.product  = A18
TableOne.qty      = 7
TableOne.sequence = 1534334750278856541 
TableTwo.sequence = 1534334750278856540
TableTwo.size     = 5

谢谢

1 个答案:

答案 0 :(得分:2)

首先编写一个子查询,以找到符合条件的tableTwo中的序列号:

SELECT t1.product, t1.sequence AS t1_sequence, t1.qty, MAX(t2.sequence) AS t2_sequence
FROM tableOne AS t1
JOIN tableTwo AS t2 ON t1.product = t2.t2.product AND t1.SEQUENCE >= t2.sequence
GROUP BY t1.product

然后将其与tableTwo一起查找包含该序列的整行。

SELECT product, t1_sequence, t2_sequence, qty, t2_sequence, t2.size
FROM (
    SELECT t1.product, t1.sequence AS t1_sequence, t1.qty, MAX(t2.sequence) AS t2_sequence
    FROM tableOne AS t1
    JOIN tableTwo AS t2 ON t1.product = t2.t2.product AND t1.SEQUENCE >= t2.sequence
    GROUP BY t1.product
) AS joined
JOIN tableTwo AS t2 ON t2.product = joined.product AND t2.sequence = joined.t2_sequence
相关问题