Pages

Showing posts with label Mysql Group CONCAT. Show all posts
Showing posts with label Mysql Group CONCAT. Show all posts

Monday, July 2, 2018

MYSQL Comma Seperated Rows | Concatenate multiple MySQL rows into one field

Tips Trick to Concatenate comma separated rows Value:

Suppose you want to show comma separate row value using mysql query and want output like below:

Mysql query to get favorite subject of Person :

SELECT subjects FROM user_subject_table WHERE user_id = 5; 

It will Give below output:

subjects
Computer
History
English
Chemistry

But you want to show comma separate in single row with user id then use below query:

SELECT user_id, GROUP_CONCAT(subjects SEPARATOR ', ') as fav_subject
FROM user_subject_table GROUP BY user_id

Output:

user_id          fav_subject
2                     English, Computer
5                     Computer, History, English, Chemistry

Advance Usage : 
1. Show Distinct subjects

SELECT user_id, GROUP_CONCAT(DISTINCT subjects  SEPARATOR ', ') as fav_subject

FROM user_subject_table GROUP BY user_id

2.  Show Subject Order by (ASC or DESC)

SELECT user_id , GROUP_CONCAT(subjects  ORDER BY subjects  ASC SEPARATOR ', ') as fav_subject FROM user_subject_table GROUP BY user_id