[英]Fetch only last matched row from joined table in Laravel 8 eloquent using table join
[英]How to return a joined table with last matched results from the second table?
表一摘录:
┌─product─────┬────────────sequence─┬─qty─┐
│ A18 │ 1534334750278856541 │ 7 │
└─────────────┴─────────────────────┴─────┘
表二摘录:
┌────────────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
谢谢
首先编写一个子查询,在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.