mysql分组、合并语句

时间:2019-08-30
本文章向大家介绍mysql分组、合并语句,主要包括mysql分组、合并语句使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

MySQL中group_concat函数 
完整的语法如下: 
group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符']) 

数据如下: 

Sql代码  
  1. mysql> select * from aa;  
  2. +------+------+  
  3. | id| name |  
  4. +------+------+  
  5. |1 | 10|  
  6. |1 | 20|  
  7. |1 | 20|  
  8. |2 | 20|  
  9. |3 | 200 |  
  10. |3 | 500 |  
  11. +------+------+  
  12. rows in set (0.00 sec)  





1.以id分组,把name字段的值打印在一行,逗号分隔(默认) 

Sql代码  
  1. mysql> select id,group_concat(name) from aa group by id;  
  2. +------+--------------------+  
  3. | id| group_concat(name) |  
  4. +------+--------------------+  
  5. |1 | 10,20,20|  
  6. |2 | 20 |  
  7. |3 | 200,500|  
  8. +------+--------------------+  
  9. rows in set (0.00 sec)  



2.以id分组,把name字段的值打印在一行,分号分隔 

Sql代码  
  1. mysql> select id,group_concat(name separator ';') from aa group by id;  
  2. +------+----------------------------------+  
  3. | id| group_concat(name separator ';') |  
  4. +------+----------------------------------+  
  5. |1 | 10;20;20 |  
  6. |2 | 20|  
  7. |3 | 200;500 |  
  8. +------+----------------------------------+  
  9. rows in set (0.00 sec)  



3.以id分组,把去冗余的name字段的值打印在一行,逗号分隔 

Sql代码  
  1. mysql> select id,group_concat(distinct name) from aa group by id;  
  2. +------+-----------------------------+  
  3. | id| group_concat(distinct name) |  
  4. +------+-----------------------------+  
  5. |1 | 10,20|  
  6. |2 | 20 |  
  7. |3 | 200,500 |  
  8. +------+-----------------------------+  
  9. rows in set (0.00 sec)  



4.以id分组,把name字段的值打印在一行,逗号分隔,以name排倒序 

Sql代码  
    1. mysql> select id,group_concat(name order by name desc) from aa group by id;  
    2. +------+---------------------------------------+  
    3. | id| group_concat(name order by name desc) |  
    4. +------+---------------------------------------+  
    5. |1 | 20,20,10 |  
    6. |2 | 20|  
    7. |3 | 500,200|  
    8. +------+---------------------------------------+  
    9. rows in set (0.00 sec)  

原文地址:https://www.cnblogs.com/wgyi140724-/p/11437476.html