简体   繁体   中英

Query with GROUP_CONCAT not working

I have 3 tables with the following structure:

**users**
id 
first_name
last_name


**specialties**
specialty_id
specialty_name


**user_specialties**
user_id
specialty_id

Here is some sample data:

**users**
1  Bill  Smith
2  Tom   Jones
3  Jill  Hayes


**specialties**
1  word
2  web
3  database

**user_specialties**
1  1
2  1
2  3
3  2
3  3

I need to query the data so the specialties are concatinated on one row like the below output

**Desired Result**
Bill  Smith  word
Tom   Jones  word,database
Jill  Hayes  web,database

I am using the following query

SELECT
users.first_name,
users.last_name,
GROUP_CONCAT(specialties.specialtyname)
FROM
users 
LEFT JOIN user_specialties ON user_specialties.user_id = users.userid
RIGHT JOIN specialties ON user_specialties.specialty_id = specialties.specialty_id

It is not working...

You're missing a GROUP BY clause. Most likely it should be GROUP BY users.id , and it'd go AFTER the JOIN lines.

I just tested this query

SELECT first_name,last_name,group_concat(specialty_name) 
FROM user_specialties map 
INNER JOIN specialties skill on user.id = map.user_id 
INNER JOIN users user ON skill.specialty_id = map.specialty_id 
GROUP BY user.id

Cheers! :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM