繁体   English   中英

Mysql - 如何避免 group by 但仍然使用 concat 和 group concat 我需要组合多列和多行结果

[英]Mysql - How do I avoid group by but still with concat and group concat I would need to combine multiple columns and rows results

我在桌子上有类似的东西

mysql> select uuid , short-uuid FROM sampleUUID WHERE identifier ="test123";
+--------------------------------------+-------------+
|       uuid                           | short-uuid   |
+--------------------------------------+-------------+
| 11d52ebd-1404-115d-903e-8033863ee848 | 8033863ee848 |
| 22b6f783-aeaf-1195-97ef-a6d8c47261b1 | 8033863ee848 |
| 33c51085-ccd8-1119-ac37-332510a16e1b | 332510a16e1b |
+--------------------------------------+-------------+

我需要这样的结果(全部分组在单行中,单值 w.r.t uuid 和 short-uuid 相同)

| uuidDetails                                                         
+----------------------------------------------------------------------------------------------------------------+-------------+
| 11d52ebd-1404-115d-903e-8033863ee848,22b6f783-aeaf-1195-97ef-a6d8c47261b1|8033863ee848&&33c51085-ccd8-1119-ac37-332510a16e1b| 332510a16e1b |
+----------------------------------------------------------------------------------------------------------------+-------------+

(基本上将 uuid 和短 uuid 从多行和多列中分组到单行中)

我知道这可以通过select GROUP_CONCAT(uuid)FROM sampleUUID WHERE identifier ="test123" group by short-uuid; 但我不想在这里使用 group by,因为这会给出多行,我需要全部放在一行中。

我尝试了以下内容,但未能在单行中获得结果

select ANY_VALUE(CONCAT_WS( '||',CONCAT_WS('|',GROUP_CONCAT(uuid) SEPARATOR ','),short-uuid)) )as uuidDetails from sampleUUID 
where identifier ="test123";

这导致如下所示,没有正确附加短 uuid(这里只附加了 1 个短 uuid,实际上需要将前 2 个 uuid 和 1 个短(因为相同的短 uuid)uuid 和第 3 个 uuid 与其他短 uuid 分组)

| uuidDetails                                                         
+----------------------------------------------------------------------------------------------------------------+-------------+
| 11d52ebd-1404-115d-903e-8033863ee848,22b6f783-aeaf-1195-97ef-a6d8c47261b1,33c51085-ccd8-1119-ac37-332510a16e1b| 332510a16e1b |
+----------------------------------------------------------------------------------------------------------------+-------------+

这不是我所期望的

这里的任何帮助将不胜感激。 谢谢

使用嵌套查询。

SELECT GROUP_CONCAT(result ORDER BY result SEPARATOR '&&') AS uuidDetails
FROM (
    SELECT CONCAT(GROUP_CONCAT(uuid ORDER BY uuid SEPARATOR ','), '|', short_uid) AS result
    FROM sampleUUID
    WHERE identifier = 'test123'
    GROUP BY short_uid
) AS x

注意:如果不需要对 UUID 值进行排序,我们可以在GROUP_CONCAT聚合中使用ORDER BY以使结果更具确定性,因此在给定相同数据的情况下,查询将仅返回多个可能结果之一,例如 return aa,bb|1&&cc|3而不是bb,aa|1&&cc|3cc|3&&aa,bb|1cc|3&&bb,aa|1

暂无
暂无

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

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