如何在MySQL中查询concat,group_concat,group for多个子​​查询

时间:2015-08-13 03:06:31

标签: mysql group-by group-concat

我有数据库结构和数据:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="slide-content">
  <ul class="container">
    <li>Ele 1</li>
    <li>Ele 2</li>
    <li>Ele 3</li>
    <li>Ele 4</li>
    <li>Ele 5</li>
    <li>Ele 6</li>
    <li>Ele 7</li>
    <li>Ele 8</li>
    <li>Ele 9</li>
    <li>Ele 10</li>
  </ul>
</div>

请帮我查询这样的结果?

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

1 个答案:

答案 0 :(得分: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)