2016-06-09 37 views
1

一個例子的兩個不同的列的值,以表明該問題:的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行應該被「合併」到一行與datenumber(以及可選地argIDdependentArgID)這些行的。

我試了一下,是自加入,但我沒有得到正確的行分組:

無法正常工作(並沒有額外的結果字段):

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`; 
+0

而ID總是順序的(增量,並沒有差距)? – Strawberry

+0

你不能指望。解決方案必須獨立於任何數量的ID序列。該ID是一個自動增量值,可能會產生差距 – lsblsb

+0

爲什麼argID 1在結果集中出現兩次? – Strawberry

回答

0

第一次嘗試(見我的文章)指出了正確的方向。

正確的解決方法是:

SELECT `b`.`argID`, `b`.`date`, `b`.`dependentArgID`, `a`.`number` 
FROM `table` `a` 
CROSS JOIN `table` `b` 
ON `a`.`ID` = `b`.`dependentID` 
WHERE `a`.`argID` = 2 AND `b`.`date` IS NOT NULL 
GROUP BY `a`.`dependentID`; 

由於對大腦的刺激所有的幫手。

+0

你依賴於你的答案中的ID(什麼不是我想要的)。並且您正在使用子查詢。必須驗證哪些更有效。 – lsblsb