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
The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.
The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.
To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement.
MySQL has the GROUP_CONCAT() function that allows us to output our query results in a comma separated list: SELECT GROUP_CONCAT(PetName) FROM Pets; Oracle Database. SQL Server.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With