MySQL - 查询在字段中返回CSV?

时间:2011-11-27 09:30:28

标签: mysql

假设我有以下表格:

TABLE: foo
- foo_id (PK)

TABLE: tag
- tag_id (PK)
- name

TABLE: foo_tag
- foo_tag_id (PK)
- foo_id (FK)
- tag_id (FK)

如何查询,以便得到如下结果:

==========================
| foo_id | tags          |
==========================
| 1      | foo, bar      |
| 2      | foo           |
| 3      | bar           |
--------------------------

基本上,我需要在一列中以逗号分隔所有foo个标签。可能在MySQL?

2 个答案:

答案 0 :(得分:1)

select f.foo_id, GROUP_CONCAT(t.name) as tags
from foo f, tag t, foo_tag as ft
where f.foo_id = ft.foo_id and ft.tag_id = t.tag_id
group by f.foo_id

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

答案 1 :(得分:0)

SELECT 
     f.foo_id, 
     GROUP_CONCAT(t.name separator ', ') as tags
FROM 
     foo f, 
     tag t, 
     foo_tag as fOt
WHERE f.foo_id = fOt.foo_id 
AND fOt.tag_id = t.tag_id
GROUP BY f.foo_id

这里我使用逗号和空格作为分隔符。