我有3张桌子:
categories:
ID, category
"1","Cars"
"2","Trucks"
"3","Bikes"
"4","Planes"
"5","Boats"
users:
ID, username
"1","john"
"2","bob"
"3","billy"
users_categories:
ID, userid, categoryid
"1","1","2"
"2","1","5"
"3","2","3"
"4","3","2"
"5","3","4"
"6","3","5"
Q1。我想要的是:
john,Trucks,Boats
bob,Bikes
billy,Trucks,Planes,Boats
我来到这里。类别的Concat会做。
SELECT U.`username`, (SELECT C.`category` FROM `categories` C LEFT JOIN `users_categories` UC ON C.`ID` = UC.`categoryid` WHERE U.ID = UC.userid) FROM `users` U
但是我得到#1242 - 子查询返回超过1行。
Q2。有没有更好的方法来构建它?不会有超过50-100个类别。
答案 0 :(得分:4)
使用 GROUP_CONCAT
来实现您的目标
SELECT a.username,
GROUP_CONCAT(c.category)
FROM users a
INNER JOIN users_categories b
On a.Id = b.userID
INNER JOIN categories c
ON b.categoryID = c.ID
GROUP BY a.ID
答案 1 :(得分:0)
如果您可以将类别作为逗号分隔字符串,则可以使用GROUP_CONCAT函数。
让我们看看(我从未在mysql中尝试过自己)
select u.username,
GROUP_CONCAT(DISTINCT c.Category order by c.Category SEPARATOR ',')
from users u
join usersCategories uc
on u.ID = uc.userID
join Categories c
on c.ID = uc.CategoryID
您可能需要将其调整为MySQL特定语法,抱歉。