mysql select join:一对多关系

时间:2017-04-25 18:06:37

标签: mysql sql

我有2张桌子

table: wiki_articles

wiki_article_id | title      | slug
---------------------------------------
1               | title 1    | title-1
2               | title 2    | title-2

table: wiki_articles_text

wiki_article_text_id | wiki_article_id | text | timestamp
---------------------------------------------------------
1                    | 1               | ...  | 2017-04-25 12:00:00
2                    | 1               | ...  | 2017-04-25 12:30:00
3                    | 2               | ...  | 2017-04-25 13:00:00
4                    | 2               | ...  | 2017-04-25 13:30:00

我想选择所有文章以及每篇文章的最新文本。

到目前为止我的查询:

        $q = "  SELECT      a.wiki_article_id,
                            a.title,
                            a.slug,
                            t1.text,
                            t1.timestamp
                FROM
                            wiki_articles AS a
                JOIN
                            wiki_articles_texts AS t1
                        ON
                            a.wiki_article_id = t1.wiki_article_id
                LEFT OUTER JOIN
                            wiki_articles_texts AS t2
                        ON
                            (a.wiki_article_id = t2.wiki_article_id AND (t1.timestamp < t2.timestamp OR t1.timestamp = t2.timestamp AND t1.wiki_article_text_id < t2.wiki_article_text_id))
                WHERE
                            t2.wiki_article_text_id IS NULL";

这不起作用。我已经用这个问题(SQL join: selecting the last records in a one-to-many relationship)来尝试,因为我认为这是同样的问题。

我的查询有什么问题?

编辑:我发现了一个错误,现在可以使用了。我忘记将'1'添加到t1.wiki_article_id

1 个答案:

答案 0 :(得分:0)

您可以通过wiki_article_id

在max my_timestamp组上使用内部联接
$q = "  SELECT      a.wiki_article_id,
                        a.title,
                        a.slug,
                        t1.text,
                        t1.timestamp
            FROM    wiki_articles AS a
            JOIN    wiki_articles_texts AS t1  ON  a.wiki_article_id = t1.wiki_article_id
            INNER   JOIN ( 
              select wiki_article_id, max(timestamp) as  my_timestamp
              from wiki_articles_texts 
              group by wiki_article_id
     ) t2 on  a.wiki_article_id = t2.wiki_article_id and t1.timestamp = t1.my_timestamp";