一個例子的兩個不同的列的值,以表明該問題:的MySQL:聯合兩個相關聯的行分別
ID: The primary key.
argID: A foreign key pointing to another table.
dependentID: A foreign key pointing to the field ID of the table itself.
dependentArgID: A foreign key pointing to the same table as argID.
欲兩個相關聯的行分別結合(具有相同dependentID)組合成一個結果行,總是選擇第一的日期和下一行的數量:
ID argID dependentID dependentArgID date number
1 1 2 2 2016-06-06 null
2 2 2 null null 1
3 1 4 2 2016-06-07 null
4 2 4 null null 2
...
期望的結果:
argID date dependentArgID number
1 2016-06-06 2 1
1 2016-06-07 2 2
...
問題在短形式:要以相同的dependentID
行應該被「合併」到一行與date
和number
(以及可選地argID
和dependentArgID
)這些行的。
我試了一下,是自加入,但我沒有得到正確的行分組:
無法正常工作(並沒有額外的結果字段):
SELECT `b`.`date`, `a`.`number`
FROM `table` `a` LEFT JOIN `table` `b` ON `a`.`argID` = `b`.`dependentArgID`
WHERE `a`.`argID` = 2
GROUP BY `a`.`dependentID`;
而ID總是順序的(增量,並沒有差距)? – Strawberry
你不能指望。解決方案必須獨立於任何數量的ID序列。該ID是一個自動增量值,可能會產生差距 – lsblsb
爲什麼argID 1在結果集中出現兩次? – Strawberry