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