我有以下问题:我有三个表,一个用户表,一个类别表和一个user_category表,它将两个第一个表连接到foregn键。
用户表:
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
有可能这样做吗?
答案 0 :(得分:2)
SELECT users.id, users.username, GROUP_CONCAT(categories.category) as cats
FROM user_category
INNER JOIN users ON users.id = user_category.user_id
LEFT JOIN categories ON categories.id = user_category.category_id
GROUP BY users.id, users.username
可以做你想做的事。
请参阅http://www.sqlines.com/mysql/functions/group_concat
使用TSQL,您可以使用How Stuff and 'For Xml Path' work in Sql Server
之类的smth