我正在嘗試構建一個視圖/查詢,該視圖/查詢在多個連接中跳躍,每個左側記錄顯示一個結果行,右側記錄是表中該物件的最新創建記錄。
最終目標是向前端應用程式提供資料,但我需要能夠判斷右側表中是否沒有資料,同時仍顯示左側表中的資料。
我不知道我說得好不好;我有點超出我的深度。也許代碼會比英語更好地說明。這里有一些表格來說明:
左手桌bill
id description extId
1 Some descr... SB 123
2 Another de... SB 124
3 Third desc... SB 125
連接表tally_bill
id billId tallyId
1 2 1
2 2 2
3 3 3
4 3 4
請注意,沒有billId = 1 的條目
右手桌tally
id countYes countNo created
1 4 0 2022-09-26 13:11:48
2 5 8 2022-09-26 14:50:24
3 10 11 2022-09-26 11:20:01
4 4 3 2022-09-26 13:41:25
我想要的結果看起來像這樣:
billId description extId countYes countNo
1 Some descr... SB 123 null null
2 Another de... SB 124 5 8
3 Third desc... SB 125 4 3
我需要countYes并countNo成為 中最近創建的記錄中的值tally。
到目前為止我得到的查詢是:
SELECT
bill.id, bill.description, bill.extId,
tally.id, tally.countYes, tally.countNo
FROM
bill
LEFT JOIN tally_bill
ON tally_bill.billId = bill.id
LEFT JOIN tally
ON tally.id = tb.tallyId
AND (
SELECT
MAX(tally.id)
FROM
tally_bill tb
WHERE
tb.billId = bill.id);
但這會產生以下效果:
billId description extId id countYes countNo
2 Another de... SB 124 2 5 8
3 Third desc... SB 125 4 4 3
如您所見,記錄billId = 1丟失了。我對這個查詢做了一些變化,移動子查詢,嘗試分組和磁區等,但無濟于事。我在我的 SQL-fu 的極限,所以我將不勝感激任何幫助或啟發,請:)
我正在使用 MySQL 8.0.30,但如果需要更改版本,我愿意接受。
uj5u.com熱心網友回復:
select id
,description
,extId
,countYes
,countNo
from (
select b.id
,b.description
,b.extId
,t.countYes
,t.countNo
,row_number() over(partition by b.id order by t.id desc) as rn
from bill b left join tally_bill tb on tb.billId = b.id left join tally t on t.id = tb.tallyId
) t
where rn = 1
| ID | 描述 | 分機號 | 計數是 | 計數否 |
|---|---|---|---|---|
| 1 | 一些描述 | SB 123 | 無效的 | 無效的 |
| 2 | 另一個德 | SB 124 | 5 | 8 |
| 3 | 第三個描述 | SB 125 | 9 | 4 |
小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516148.html
標籤:mysqlsql加入
