1.原始sql:
mysql> select (select t.name from dimension t where t.id=rule_dimension.dimension_id) as name,getDimensionValue(rule_id,dimension_id,2) as 'vts' from rule_dimension where rule_id=1 and status=0; +------+-----------+ | name | vts | +------+-----------+ | 地域 | 北京,上海 | | 时段 | 4点 | | 频道 | 科技 | +------+-----------+
即:把多行数据显示到一行——行转列。这里主要用到了group_concat函数
2.把两列数据合并成一列显示:
select concat_ws(':',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getDimensionValue(rule_id,dimension_id,2)) as ct from rule_dimension where rule_id=1 and status=0; +----------------+ | ct | +----------------+ | 地域:北京,上海 | | 时段:4点 | | 频道:科技 | +----------------+ 3 rows in set
3.把多行转换成一行显示(行转列)
select group_concat(concat_ws(':',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getDimensionValue(rule_id,dimension_id,2)) SEPARATOR ' and ') as ct from rule_dimension where rule_id=1 and status=0; +---------------------------------------+ | ct | +---------------------------------------+ | 地域:北京,上海 and 时段:4点 and 频道:科技 | +---------------------------------------+ 1 row in set这里主要用到了group_concat函数,可以使用separator指定连接符号;
4.修正结果
select group_concat(concat_ws(':(',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getDimensionValue(rule_id,dimension_id,2)) SEPARATOR ') and ') as ct from rule_dimension where rule_id=1 and status=0; +----------------------------------------------+ | ct | +----------------------------------------------+ | 地域:(北京,上海) and 时段:(4点) and 频道:(科技 | +----------------------------------------------+ 1 row in set这里主要还是用到了concat_ws函数,把括号加上了
5.补充最后一个括号:
select concat(group_concat(concat_ws(':(',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getDimensionValue(rule_id,dimension_id,2)) SEPARATOR ') and '),')') as ct from rule_dimension where rule_id=1 and status=0; +-----------------------------------------------+ | ct | +-----------------------------------------------+ | 地域:(北京,上海) and 时段:(4点) and 频道:(科技) | +-----------------------------------------------+ 1 row in set