2015-08-13 119 views
0

我有数据库结构和数据:如何在MySQL查询CONCAT,GROUP_CONCAT,按多子查询

id | total | type | value_1 | value_2 
1 | 9 | 1 | 10 | 20 
2 | 9 | 1 | 21 | 30 
3 | 10 | 1 | 31 | 40 
4 | 9 | 2 | 41 | 50 
5 | 9 | 2 | 51 | 60 
6 | 8 | 2 | 61 | 70 

请帮助我如何查询这样的结果呢?

type || total || id ||  value 
1 || 9|10 || 1,2|3 || 10-20,21-30|31-40 
2 || 9|8 || 4,5|6 || 41-50,51-60|61-70 
+0

此刻,我只能通过总的查询组,当试图按 型 选择 \t总, \t GROUP_CONCAT我有点困难(ID SEPARATOR“|”)为ID , \t GROUP_CONCAT( \t \t CONCAT_WS( \t \t \t ' - ', \t \t \t _1, \t \t \t _2 \t \t)SEPARATOR '|' \t)AS值 FROM \t表 GROUP BY \t总 –

回答

0

这应该一旦你改变表名。诀窍是分阶段构建它。首先,合并value_1value_2,然后按总数分组,然后使用,作为分隔符,最后按|分组。

select type, 
group_concat(distinct total separator '|') as total, 
group_concat(distinct id separator '|') as id, 
group_concat(distinct vals separator '|') as vals 
from (select type, 
    group_concat(distinct total separator ',') as total, 
    group_concat(distinct id separator ',') as id, 
    group_concat(distinct vals separator ',') as vals, 
    count(id) as count 
    from (select id, total, type, concat(value_1,'-',value_2) as vals from tbl) as a 
    group by total, type order by count desc) as b 
group by type; 

我复制你的表,所以我可以测试出来

mysql> select * from tbl; 
+------+-------+------+---------+---------+ 
| id | total | type | value_1 | value_2 | 
+------+-------+------+---------+---------+ 
| 1 |  9 | 1 |  10 |  20 | 
| 2 |  9 | 1 |  21 |  30 | 
| 3 | 10 | 1 |  31 |  40 | 
| 4 |  9 | 2 |  41 |  50 | 
| 5 |  9 | 2 |  51 |  60 | 
| 6 |  8 | 2 |  61 |  70 | 
+------+-------+------+---------+---------+ 
6 rows in set (0.00 sec) 

下面是结果。

mysql> select type, 
-> group_concat(distinct total separator '|') as total, 
-> group_concat(distinct id separator '|') as id, 
-> group_concat(distinct vals separator '|') as vals 
-> from (select type, 
-> group_concat(distinct total separator ',') as total, 
-> group_concat(distinct id separator ',') as id, 
-> group_concat(distinct vals separator ',') as vals, 
-> count(id) as count 
-> from (select id, total, type, concat(value_1,'-',value_2) as vals from tbl) as a 
-> group by total, type order by count desc) as b 
-> group by type; 
+------+-------+-------+-------------------+ 
| type | total | id | vals    | 
+------+-------+-------+-------------------+ 
| 1 | 9|10 | 1,2|3 | 10-20,21-30|31-40 | 
| 2 | 9|8 | 4,5|6 | 41-50,51-60|61-70 | 
+------+-------+-------+-------------------+ 
2 rows in set, 1 warning (0.00 sec) 
+0

1型 - >总(9和10 => 9 | 10) - >总9具有的ID 1和2共有10个id 3 - > 1,2 | 3 类型2 - >总数(9和8 => 9 | 8) - >总数9有id 4和5,总数为id 6 => 4,5 | 6 请帮我检查一下你的查询字符串。 –

+0

使用'|'与使用'''的规则是什么? –

+0

我希望的结果:(请参阅美容格式的#1) type ||总|| id ||值 1 || 9 | 10 || 1,2 | 3 || 10-20,21-30 | 31-40 2 || 9 | 8 || 4,5 | 6 || 41-50,51-60 | 61-70 –