我的数据库中有两个表:
人员
user_id | user_name | email |
1 Jack ...
2 Annie ...
收藏夹颜色
user_id | color_name |
1 black
1 green
2 blue
如何通过用户名显示所有喜欢的颜色?如何在获取时拆分这些多个值?
显示示例:插孔:黑色,绿色|安妮:蓝色
我的sql就像:
SELECT user_name, GROUP_CONCAT(color_name SEPARATOR ', ')
FROM Persons
LEFT JOIN favoriteColors ON Persons.user_id = favoriteColors.user_id
GROUP BY Persons.user_id
LIMIT {$limit} OFFSET {$offset}
({$limit
和$offset
由ajax发送)
答案 0 :(得分:0)
您可以为此目的使用以下汇总功能
https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_json-arrayagg https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_json-objectagg
SELECT p.user_id, GROUP_CONCAT(DISTINCT p.user_name) name, JSON_ARRAYAGG(f.color_name) colors
FROM Persons p
LEFT JOIN favoriteColors f ON p.user_id = f.user_id
WHERE p.user_name = {$username}
GROUP BY p.user_id
LIMIT {$limit} OFFSET {$offset}