在MySQL中按特定顺序选择GROUP_CONCAT行

时间:2013-05-08 10:47:43

标签: mysql

我有一个名为“tblVersion”的表,看起来像......

| key           |  value  |
|-------------------------|
| buildVersion  |  5      |
| minorVersion  |  4      |
| majorVersion  |  2      |

我想构建一个返回字符串“2.4.5”的查询,即majorVersion.minorVersion.buildVersion。

到目前为止我已经

SELECT GROUP_CONCAT(tblVersion.value SEPARATOR '.' ) AS softwareVersion 
FROM tblVersion 
WHERE tblVersion.key = 'majorVersion'
OR tblVersion.key = 'minorVersion' OR tblVersion.key = 'buildVersion'

这会返回“5.2.4”,我似乎无法按正确的顺序获取字符串。

是否可以具体说明值的显示顺序?

3 个答案:

答案 0 :(得分:2)

FIELD

使用订单
SELECT GROUP_CONCAT(value order by  FIELD(tblVersion.key , 'majorVersion', 'minorVersion' , 'buildVersion') SEPARATOR '.' ) AS softwareVersion 
FROM tblVersion
WHERE tblVersion.key = 'majorVersion'
OR tblVersion.key = 'minorVersion' OR tblVersion.key = 'buildVersion';

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field

演示:http://sqlfiddle.com/#!2/8ef367/4

答案 1 :(得分:2)

您应该能够在CASE函数中使用GROUP_CONCAT表达式:

select
  group_concat(`value` 
               order by 
                 case `key` 
                   when 'majorVersion' then 0 
                   when 'minorVersion' then 1
                   else 'buildVersion' end SEPARATOR '.') SoftwareVersion
from tblVersion

请参阅SQL Fiddle with Demo

答案 2 :(得分:0)

如果DhruvPathak关于你真正追求的是什么,那么就可以通过这种方式实现......

SELECT GROUP_CONCAT(x.value ORDER BY FIELD(x.key,'minorversion','majorversion','buildversion') DESC SEPARATOR '.') softwareVersion 
  FROM tblversion x 
 WHERE x.key IN('minorVersion','majorVersion','buildVersion');