【发布时间】:2017-11-11 03:13:52
【问题描述】:
我有以下问题:我有三个表,一个用户表,一个类别表和一个 user_category 表,它用外键连接前两个表。
用户表:
id username
1 user1
... ...
类别表:
id category
1 test1
2 test2
3 test3
... ...
user_category 表
id user_id category_id
1 1 1
2 1 2
3 1 3
现在我想选择所有用户及其类别,但我不想拥有同一用户的多行 - 相反,我想将用户的所有类别合并到一个类别字段中。
SELECT users.*, categories.category FROM user_category INNER JOIN users ON users.id = user_category.user_id LEFT JOIN categories ON categories.id = user_category.category_id
输出:
id username category
1 user1 test1
1 user1 test2
1 user1 test3
但我想要以下内容:
id username category
1 user1 test1, test2, test3
有可能这样做吗?
【问题讨论】:
-
test1, test2, test3你不应该那样做,应该学习如何规范你的数据库 -
使用 GROUP_CONCAT 并按用户名分组