簡體   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