【问题标题】:Group join with many to one in one row多对一排成组加入
【发布时间】:2013-12-19 17:02:49
【问题描述】:

我希望得到一些帮助。我想加入一个一对多的数据库,并显示表“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   

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

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

【问题讨论】:

  • 数据显示问题通常最好在表示层/应用程序级代码中处理(例如,作用于有序数组的简单 PHP 循环)。如果你决心在 MySQL 中解决这个问题,那么我可能会建议提供适当的 DDL。

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


【解决方案1】:

如果将价值观结合起来,它对你有用吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多