關於mysql函式GROUP CONCAT

2021-06-25 21:42:37 字數 2570 閱讀 6566

group_concat()是mysql資料庫提供的乙個函式,通常跟group by一起用,具體可參考mysql官方文擋:

語法:group_concat([distinct] expr [,expr ...] [order by [asc | desc] [,col_name ...]] [separator str_val])

1.例如:

select student_id, group_concat(courses_id) as courses from student_courses where student_id=2 group by student_id; 

+------------+---------+ 

| student_id | courses | 

+------------+---------+ 

| 2 | 3,4,5 |

+------------+---------+ 

這 就不需要用php迴圈了

$row = $pdo->query("select student_id, group_concat(courses_id) as courses from student_courses where student_id=2 group by student_id");

$result = explode(',', $row['courses']); 

2.當然分隔符還可以自定義,預設是以「,」作為分隔符,若要改為「|||」,則使用separator來指定,例如:

select student_id, group_concat(courses_id separator '|||') as courses from student_courses where student_id=2 group by student_id;

+------------+---------+ 

| student_id | courses | 

+------------+---------+ 

| 2          |3|||4|||5 |

+------------+---------+ 

3.除此之外,還可以對這個組的值來進行排序再連線成字串,例如按courses_id降序來排:

select student_id, group_concat(courses_id order by courses_id desc) as courses from student_courses where student_id=2 group by student_id;

+------------+---------+ 

| student_id | courses | 

+------------+---------+ 

| 2          | 5,4,3 |

+------------+---------+ 

4.需要注意的:

a.int欄位的連線陷阱

當你用group_concat的時候請注意,連線起來的字段如果是int型,一定要轉換成char再拼起來,

否則在你執行後(executescalar或者其它任何執行sql返回結果的方法)返回的將不是乙個逗號隔開的串,

而是byte。

該問題當你在sqlyog等一些工具中是體現不出來的,所以很難發現。

select group_concat(ipaddress) from t_ip 返回逗號隔開的串

select group_concat(id) from t_ip 返回byte

select group_concat(cast(id as char)) from t_dep 返回逗號隔開的串

select group_concat(convert(id , char)) from t_dep 返回逗號隔開的串

附cast,convert的用法:

cast(expr as type), convert(expr,type) , convert(expr using transcoding_name)

cast() 和convert() 函式可用來獲取乙個型別的值,並產生另乙個型別的值。

這個型別 可以是以下值其中的 乙個:

binary[(n)]

char[(n)]

date

datetime

decimal

signed [integer]

time

unsigned [integer]

b.長度陷阱

用了group_concat後,select裡如果使用了limit是不起作用的.

用group_concat連線欄位的時候是有長度限制的,並不是有多少連多少。但你可以設定一下。

使用group_concat_max_len系統變數,你可以設定允許的最大長度。

程式中進行這項操作的語法如下,其中 val 是乙個無符號整數:

set [session | global] group_concat_max_len = val;

若已經設定了最大長度, 則結果被截至這個最大長度。

在sqlyog中執行 set global group_concat_max_len = 10 後,重新開啟sqlyog,設定就會生效。

關於mysql函式GROUP CONCAT

關於mysql函式group concat miky group concat 是mysql資料庫提供的乙個函式,通常跟group by一起用,具體可參考mysql官方文擋 語法 group concat distinct expr expr orderby asc desc col name se...

關於mysql函式GROUP CONCAT

group concat 是mysql資料庫提供的乙個函式,通常跟group by一起用,具體可參考mysql官方文擋 語法 group concat distinct expr expr order by asc desc col name separator str val 1.例如 selec...

關於mysql函式GROUP CONCAT

group concat 是mysql資料庫提供的乙個函式,通常跟group by一起用,具體可參考mysql官方文擋 語法 group concat distinct expr expr order by asc desc col name separator str val 1.例如 selec...