mysql - 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
语句。
解决方案
您可以聚合和使用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
推荐阅读
- ios - UINavigationBar 后退按钮在关闭搜索栏后总是变为蓝色
- python - 无法使用 Python 请求登录网站
- javascript - 使用按钮播放音频并在再次单击按钮时重新开始播放
- outlook-web-addins - 无法访问 userProfile.displayName 的属性
- linux - 模拟跟踪环境中发生错误 310170 属性节点(参数 1)
- objective-c - 由于蓝牙错误,应用商店拒绝应用
- swift - 为什么不符合协议可编码可解码?
- load-balancing - 当循环可以均匀分配流量时,为什么我们需要一致的哈希
- c# - 在读取内容之前从套接字接收全部数据
- java - 如果名称中有空格,getResource(...).getFile() 方法将抛出 FileNotFoundException