[英]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.