【问题标题】:MySQL Inner Join Merge RowsMySQL 内连接合并行
【发布时间】:2017-11-11 03:13:52
【问题描述】:

我有以下问题:我有三个表,一个用户表,一个类别表和一个 user_category 表,它用外键连接前两个表。

用户表:

id     username

1      user1
...    ...

类别表:

id    category

1     test1
2     test2
3     test3
...   ...

user_category 表

id    user_id    category_id
1     1          1
2     1          2
3     1          3

现在我想选择所有用户及其类别,但我不想拥有同一用户的多行 - 相反,我想将用户的所有类别合并到一个类别字段中。

SELECT users.*, categories.category FROM user_category INNER JOIN users ON users.id = user_category.user_id LEFT JOIN categories ON categories.id = user_category.category_id

输出:

 id     username     category
 1      user1        test1
 1      user1        test2
 1      user1        test3

但我想要以下内容:

 id     username     category
 1      user1        test1, test2, test3

有可能这样做吗?

【问题讨论】:

  • test1, test2, test3 你不应该那样做,应该学习如何规范你的数据库
  • 使用 GROUP_CONCAT 并按用户名分组

标签: php mysql


【解决方案1】:
SELECT users.id, users.username, GROUP_CONCAT(categories.category) as cats
FROM user_category 
INNER JOIN users ON users.id = user_category.user_id 
LEFT JOIN categories ON categories.id = user_category.category_id
GROUP BY users.id, users.username

可以为所欲为。

http://www.sqlines.com/mysql/functions/group_concat

使用 TSQL,您可以使用 How Stuff and 'For Xml Path' work in Sql Server 之类的东西

【讨论】:

  • 问题是,我只为用户获取一个类别而不是全部。
  • @pete 它确实有效,这里有一个有效的示例:rextester.com/MTZROD6195 注意:我必须将 users 更改为 usersx,这样它才能在 rextester 上运行
  • 非常感谢!我不知道出了什么问题,但现在可以了。
猜你喜欢
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 2010-09-10
  • 2011-06-23
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 2013-01-20
相关资源
最近更新 更多