首页 > 解决方案 > SQL SELECT 查询,组合匹配的行,在相等的地方使用一列值,在不相等的地方使用连接

问题描述

我无法提出标题描述的查询。基本上,这是一个示例表

+-------+------+-----------+-----------+-----------+
| Class | Sect | otherCol1 | otherCol2 | otherCol3 |
+-------+------+-----------+-----------+-----------+
|  abc  | 100  |     3     |    4      |     5     |
|  def  | 100  |     5     |    6      |     7     |
|  abc  | 100  |     3     |   loco    |    guys   |
|  def  | 100  |    guys   |    6      |     77    |
+-------+------+-----------+-----------+-----------+

我希望结果是

+-------+------+-----------+-----------+-----------+
| Class | Sect | otherCol1 | otherCol2 | otherCol3 |
+-------+------+-----------+-----------+-----------+
|  abc  | 100  |     3     |    4loco  |    5guys  |
|  def  | 100  |   5guys   |    6      |     777   |
+-------+------+-----------+-----------+-----------+

重要的是组合元素的顺序保持一致。例如,如果新行显示“4loco”,则应该显示“5guys”。如果它说“loco4”,那么它应该说“guys5”。

我目前拥有的 MySQL 查询似乎接近我想要的,但它无法连接所有匹配项。一些列将保持未连接,而其他列将适当地连接。它也不会在它为给定行连接的列之间保持一致的顺序。

这是我的查询的简化版本,它与我正在运行的内容相同,但列数比我实际使用的要少:

SELECT 
    IF(
        t1.Class = t2.Class, 
        t1.Class, 
        GROUP_CONCAT(DISTINCT t1.Class SEPARATOR ' ')
    ), 
    IF(
        t1.Sect = t2.Sect, 
        t1.Sect, 
        GROUP_CONCAT(DISTINCT t1.Sect SEPARATOR ' ')
    ), 
    IF(
        t1.otherCol1 = t2.otherCol1, 
        t1.otherCol1, 
        GROuP_CONCAT(DISTINCT t1.otherCol1 SEPARATOR ' ')
    ), 
    IF(
        t1.otherCol2 = t2.otherCol2, 
        t1.otherCol2, 
        GROUP_CONCAT(DISTINCT t1.otherCol2 SEPARATOR ' ')
    ), 
    IF(
        t1.otherCol3 = t2.otherCol3, t1.otherCol3, 
        GROUP_CONCAT(DISTINCT t1.otherCol3 SEPARATOR ' ')
    ) 
FROM sample_sheet t1 
JOIN sample_sheet t2 
    ON t1.Sect = t2.Sect 
    AND t1.Class = t2.Class 
GROUP BY t1.Sect, t1.Class

所有不是串联候选的列,Class取决于Sect它们的值。如果值不相等,我只需要发生连接,因此是if语句。

标签: mysql

解决方案


您可以聚合和使用group_concat(distinct ...).

为了使顺序保持一致,您需要一个可用于对记录进行排序的列(或列的组合);我在您的数据中看不到这样的列,但我假设它存在,我称之为id

select 
    class, 
    sect, 
    group_concat(distinct otherCol1 order by id separator '') otherCol1,
    group_concat(distinct otherCol2 order by id separator '') otherCol2,
    group_concat(distinct otherCol3 order by id separator '') otherCol3
from mytable
group by 
    class, 
    sect

推荐阅读