mysql GROUP_CONCAT

*爱你&永不变心* 提交于 2020-01-01 10:00:31

问题


I want to list all users with their corropsonding user class. Here are simplified versions of my tables

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');

And this is the query statement I am trying to use but is only returning the first matching user class and not a concatenated list as hoped.

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;

Actual Output

+---------+------------+
| user_id | class_name |
+---------+------------+
|       1 | Class 1    |
|       2 | Class 2    |
|       3 | Class 1    |
+---------+------------+

Wanted Output

+---------+---------------------+
| user_id | class_name          |
+---------+---------------------+
|       1 | Class 1             |
|       2 | Class 2             |
|       3 | Class 1, Class 2    |
+---------+---------------------+

Thanks in advance


回答1:


This is not the best design, but here's the query you want:

SELECT  user_id, GROUP_CONCAT(class_name)
FROM    users
JOIN    classes
ON      FIND_IN_SET(class_id, user_class)
GROUP BY
        user_id



回答2:


This breaks rules of database normalization. Don't store many-to-many values in a comma-separated list. Instead make another table user_classes with fields user_id and class_id. This table is simply used as a link table between the other two classes. After this you can use GROUP_CONCAT to do what you want.



来源:https://stackoverflow.com/questions/2516545/mysql-group-concat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!