GROUP_CONCAT无效的查询

时间:2011-10-21 03:02:09

标签: mysql sql aggregate-functions group-concat

我有3个表格,结构如下:

**users**
id 
first_name
last_name


**specialties**
specialty_id
specialty_name


**user_specialties**
user_id
specialty_id

以下是一些示例数据:

**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

我需要查询数据,以便将特征排在一行,如下面的输出

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

我使用以下查询

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

它不起作用......

2 个答案:

答案 0 :(得分:3)

您错过了GROUP BY条款。很可能它应该是GROUP BY users.id,并且它会在JOIN行后发生。

答案 1 :(得分:1)

我刚测试了这个查询

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

干杯! : - )