繁体   English   中英

MySQL:分别合并两个相关行的两个不同列的值

[英]MySQL: Combine the values of two different columns of two associated rows respectively

举例说明问题:

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

第一次尝试(见我的帖子)指出了正确的方向。

正确的解决方案是:

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

感谢大脑刺激的所有助手。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM