[英]How do you order the results of mySQL group_concat() when all the values come from one column?
我有一個包含 3 列的簡單表: id
、 variable
和value
。 每個人都有很多用戶 ID 和很多不同的變量(確切地說是他們個人資料中的所有規格),但我一次只需要用這三件事查詢一個人。
ID | 多變的 | 價值 |
---|---|---|
1個 | 城市 | 芝加哥 |
1個 | zip | 60000 |
1個 | state | 白細胞介素 |
我正在使用一個查詢來嘗試生成:“chicagoIL60000”,但由於表格的制作方式(論壇軟件),zip 行恰好出現在 state 之前,所以結果實際上是亂序的:“chicago60000IL”。
這是我的查詢:
SELECT GROUP_CONCAT(`value` SEPARATOR "") FROM themes WHERE `id` = '1' AND `variable` IN ('city', 'state', 'zip')
我不清楚如何對其進行排序或分組,因為所有值都在一個列中,而且我找到的所有示例都涉及按特定列進行排序或分組。
我試過更改查詢中variable
數組的順序,但 mySQL 不關心這個。
我還嘗試了以下查詢,雖然給出了正確的順序,但實際上並沒有將結果連接到我想要的結果; 相反,它只包含三個字段。
select
group_concat(case when `variable` = 'city' then `value` end) as city,
group_concat(case when `variable` = 'state' then `value` end) as state,
group_concat(case when `variable` = 'zip' then `value` end) as zip
來自id
= '1' 的主題
在MySQL中,可以在GROUP_CONCAT中指定一個ORDER BY子句,使用CASE表達式得到你想要的順序:
SELECT GROUP_CONCAT(
`value`
order by case variable when 'city' then 1 when 'state' then 2 else 3 end
SEPARATOR ""
) citystzip
FROM themes
WHERE `id` = '1' AND `variable` IN ('city', 'state', 'zip')
或者,嘗試使用條件聚合並連接三個:
select concat(
group_concat(case when `variable` = 'city' then `value` end),
group_concat(case when `variable` = 'state' then `value` end),
group_concat(case when `variable` = 'zip' then `value` end)
) citystzip
from themes
where `id` = '1'
雖然我會使用 MAX 而不是 GROUP_CONCAT,它的優點是只顯示一個城市,state,如果有多行具有相同的 id/變量,則為 zip。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.