mysql group_concat的使用

語法:group_concat( [distinct] 要連接的字段 [order by 排序字段 asc/desc ] [separator '分隔符'] )

說明:通過使用distinct可以排除重複值;如果希望對結果中的值進行排序,可以使用order by子句;separator是一個字符串值,缺省爲一個逗號。

舉例說明:

現有一個用戶表user

id, name

一個標籤表tag

id, name

一個用戶和標籤的關聯表tag_entity

id, fk_tag_id, fk_entity_id

需求是查詢出用戶下的所有tag,空格分開

select 

u.id, u.name, group_concat(t.name  ORDER BY ta.name separator ' ') as tagName

from user u

left join tag_entity te on te.fk_entity_id = u.id

left join tag t on t.id = te.fk_tag_id

group by u.id

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章