组合连接多个到一个一个

时间:2013-12-19 17:02:49

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

我会喜欢一些帮助。我想加入一对多数据库并显示表'post'中一行的所有信息及其相关的元数据(很多)。我似乎无法弄明白该怎么做。

数据库称为帖子:

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

数据库名为meta:

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   

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

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

1 个答案:

答案 0 :(得分:0)

如果值组合在一起会对你有用吗?

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