2017-04-25 77 views
0

我有2個表MySQL的選擇加入:一個一對多的關係

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

回答

0

你可以使用由wiki_article_id上​​最大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";