3

我有 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 个类别。

4

2 回答 2

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
于 2012-11-09T06:52:52.220 回答
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 特定的语法。

于 2012-11-09T06:56:26.327 回答