使用 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
它不起作用...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您缺少
GROUP BY
子句。最有可能的应该是GROUP BY users.id
,并且它会在 JOIN 行之后。You're missing a
GROUP BY
clause. Most likely it should beGROUP BY users.id
, and it'd go AFTER the JOIN lines.我刚刚测试了这个查询
干杯! :-)
I just tested this query
Cheers! :-)