[英]How do you order the results of mySQL group_concat() when all the values come from one column?
I have a simple table that has 3 columns: id
, variable
, and value
.我有一个包含 3 列的简单表:
id
、 variable
和value
。 There are a lot of user IDs and a lot of different variables per person too (all the specs from their profiles to be exact), but I only need to query one person at a time with these three things.每个人都有很多用户 ID 和很多不同的变量(确切地说是他们个人资料中的所有规格),但我一次只需要用这三件事查询一个人。
id ![]() |
variable![]() |
value![]() |
---|---|---|
1 ![]() |
city![]() |
chicago![]() |
1 ![]() |
zip ![]() |
60000 ![]() |
1 ![]() |
state ![]() |
IL![]() |
I'm using a query in an attempt to produce: "chicagoIL60000", but because of how the table was made (forum software) the zip line happens to come before state, so the results is actually out of order: "chicago60000IL".我正在使用一个查询来尝试生成:“chicagoIL60000”,但由于表格的制作方式(论坛软件),zip 行恰好出现在 state 之前,所以结果实际上是乱序的:“chicago60000IL”。
This is the query I have:这是我的查询:
SELECT GROUP_CONCAT(`value` SEPARATOR "") FROM themes WHERE `id` = '1' AND `variable` IN ('city', 'state', 'zip')
I am unclear how to either ORDER or GROUP this because all the values are in a single column, and all the examples I find deal with ordering or grouping by a specific column.我不清楚如何对其进行排序或分组,因为所有值都在一个列中,而且我找到的所有示例都涉及按特定列进行排序或分组。
I've tried changing the order of the variable
array in the query, but mySQL doesn't care about that.我试过更改查询中
variable
数组的顺序,但 mySQL 不关心这个。
I have also tried the following query that, while giving the proper order, doesn't actually concatenate the results to what I want;我还尝试了以下查询,虽然给出了正确的顺序,但实际上并没有将结果连接到我想要的结果; rather, it just makes three fields.
相反,它只包含三个字段。
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
from themes where id
= '1'来自
id
= '1' 的主题
In MySQL, you can specify an ORDER BY clause in GROUP_CONCAT, and use a CASE expression to get the order you want:在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')
Alternatively, take your attempt using conditional aggregation and just concat the three:或者,尝试使用条件聚合并连接三个:
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'
Though I would use MAX instead of GROUP_CONCAT, which has the advantage of only showing one city, state, or zip if there are multiple rows with the same id/variable.虽然我会使用 MAX 而不是 GROUP_CONCAT,它的优点是只显示一个城市,state,如果有多行具有相同的 id/变量,则为 zip。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.