mysql - 如何在MySQL中查询concat、group_concat、group by进行多个子查询

标签 mysql group-by 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

最佳答案

一旦您更改表名称,这应该起作用。诀窍是分阶段建立它。首先,组合 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)

关于mysql - 如何在MySQL中查询concat、group_concat、group by进行多个子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978848/

相关文章:

MySQL group_concat() 按月排序

mysql查询获取重复记录对应的数据

php - 子查询返回多于 1 行

php - 检查 mysql 中是否出现多个字符串

Mysql 查询仅选择 GROUP_CONCAT 中具有唯一结果的行

mysql - SELECT 列表不在 GROUP BY 子句中且包含非聚合列;这与 sql_mode=only_full_group_by 不兼容

c# - 具有唯一键和值的组数据

mysql - 非法混合排序规则 MySQL 错误

php - MySQL 按确切日期查询

python - Pandas GroupBy,将新的数字列表列与另一列数字列表进行比较