MySQL group_concat 方法的使用

表关系图:

需求:
我想要查询的数据结果是:
 
我们可以内连接:
select s.id,s.name,srt.typeId,  stt.name as TypeName from scenics as s
INNER JOIN(
select * from scenics_type
) srt on srt.scenicsId=s.id
INNER JOIN(
SELECT * from scenicstype where deleted=0
)stt on stt.id=srt.typeId
得到结果是:
显然我们需要分组,合并一下数据。
select s.id,s.name,srt.typeId,  stt.name as TypeName from scenics as s
INNER JOIN(
select * from scenics_type
) srt on srt.scenicsId=s.id
INNER JOIN(
SELECT * from scenicstype where deleted=0
)stt on stt.id=srt.typeId
GROUP BY(s.id)

 

得到结果是:

但是TypeName累加成我们想要的结果。
MySQL给我们一个好用的方法实现这个目标。group_concat
select s.id,s.name,srt.typeId,   group_concat(stt.name SEPARATOR ',' )  as TypeName from scenics as s
INNER JOIN(
select * from scenics_type
) srt on srt.scenicsId=s.id
INNER JOIN(
SELECT * from scenicstype where deleted=0
)stt on stt.id=srt.typeId
GROUP BY(s.id)
结果如图:
OK 大功告成!
posted on 2012-08-25 10:27  上善若水123  阅读(4307)  评论(0编辑  收藏  举报