我想列出所有用户及其 corropsonding 用户类。这是我的表格的简化版本
CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT,
user_class VARCHAR(100),
PRIMARY KEY (user_id)
);
INSERT INTO users VALUES
(1, '1'),
(2, '2'),
(3, '1,2');
CREATE TABLE classes (
class_id INT NOT NULL AUTO_INCREMENT,
class_name VARCHAR(100),
PRIMARY KEY (class_id)
);
INSERT INTO classes VALUES
(1, 'Class 1'),
(2, 'Class 2');
这是我尝试使用的查询语句,但只返回第一个匹配的用户类,而不是希望的串联列表。
SELECT user_id, GROUP_CONCAT(DISTINCT class_name SEPARATOR ",") AS class_name
FROM users, classes
WHERE user_class IN (class_id)
GROUP BY user_id;
实际输出
+---------+------------+
| user_id | class_name |
+---------+------------+
| 1 | Class 1 |
| 2 | Class 2 |
| 3 | Class 1 |
+---------+------------+
想要的输出
+---------+---------------------+
| user_id | class_name |
+---------+---------------------+
| 1 | Class 1 |
| 2 | Class 2 |
| 3 | Class 1, Class 2 |
+---------+---------------------+
提前致谢