mysql - 一组以多对一的方式加入一排

标签 mysql select group-by one-to-many relation

我希望得到一些帮助。我想加入一个一对多数据库,并显示表“post”中一行的所有信息及其相关元(许多)。我似乎不知道该怎么做。

名为 post 的数据库:

ID      Title
1       Hello world
2       Yeah buddy
3       This is a test

名为元的数据库:

ID      postID     Value
1       1          Testing testing
2       1          This is a value
3       2          Testing 123 testing
4       2          This is a value 23
5       3          Testing testing test
6       3          This is a value yeah

我想按如下方式对查询结果进行分组:

1       Hello world        Testing testing        This is a value
2       Yeah buddy         Testing 123 testing    This is a value 23
3       This is a test     Testing testing test   This is a value yeah

MySQL 查询(到目前为止):

SELECT DISTINCT p.title, m.*
FROM post p
LEFT JOIN meta m ON p.ID = m.postID
GROUP BY p.title

仅给出的输出是:

1       Hello world        Testing testing       
2       Yeah buddy         Testing 123 testing    
3       This is a test     Testing testing test   

这真的很令人沮丧,因为我想显示所有相关字段,但我似乎无法弄清楚出了什么问题。看来“值”列每行不能存在两次......

有人可以帮忙(或给我指出正确的方向吗?)

最佳答案

如果将值组合起来,它对您有用吗?

SELECT p.title, group_concat(m.value separator ",") as values
FROM post p
LEFT JOIN meta m ON p.ID = m.postID
GROUP BY p.title

关于mysql - 一组以多对一的方式加入一排,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20687519/

相关文章:

mysql - 如何使用 MySQL 有条件 SELECT 多列?

mysql - 连接 3 个表以获得单行

php - 分组和排序问题

MySQL IFNULL ELSE

Python numpy 按字符串列的值拆分 csv 文件

python - `nth` 破坏了 pandas 中排序的数据框

mysql - 在新表中汇总数据

sql - 使用重复条目更新行

mysql - 子查询通过更新返回多于 1 行

sql - 如何在 Linq2Sql 中编写此查询