mysql分組、合併語句

MySQL中group_concat函數 
完整的語法以下: 
group_concat([DISTINCT] 要鏈接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符']) 

數據以下: mysql

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

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字段的值打印在一行,逗號分隔 spa

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)  
相關文章
相關標籤/搜索