mysql GROUP_CONCAT
Posted
by user301766
on Stack Overflow
See other posts from Stack Overflow
or by user301766
Published on 2010-03-25T14:55:29Z
Indexed on
2010/03/25
15:03 UTC
Read the original article
Hit count: 304
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
© Stack Overflow or respective owner