使用 GROUP_CONCAT 进行查询不起作用

发布于 2024-12-11 06:40:50 字数 825 浏览 0 评论 0原文

我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

掀纱窥君容 2024-12-18 06:40:51

您缺少 GROUP BY 子句。最有可能的应该是GROUP BY users.id,并且它会在 JOIN 行之后。

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

不知所踪 2024-12-18 06:40:51

我刚刚测试了这个查询

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

干杯! :-)

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! :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文