2011-11-01 49 views
1

我有兩個表作爲作者和文章。我想獲得每位作者的最新文章列表。我只想爲一位作者撰寫一篇文章。我希望它是最新的。但是,我什至不知道從哪裏開始這個SQL查詢。MySql查詢限制和訂單上加入statament

編輯

我的表結構可以simplefied這樣的:

authors: 
id 
name 
status 
seo 
articles: 
    author_id 
    title 
    text 
    date 
    seo 

編輯2

我想出了這樣的事情,有沒有什麼明顯的錯誤,你可以看到在這裏:

SELECT authors.*, 
(SELECT articles.title FROM articles WHERE author_id = authors.id ORDER BY articles.date DESC LIMIT 1) as title, 
(SELECT articles.seo FROM articles WHERE author_id = authors.id ORDER BY articles.date DESC LIMIT 1) as articleseo 
FROM authors 
WHERE authors.status = 1 
+2

你介意告訴你的數據庫結構嗎?表? –

+0

順便說一句,外鍵不會幫你在這裏 – Mikhail

+0

@GhazanfarMir:已添加。 – yasar

回答

1

好吧,我發現了什麼,我需要做的:

CREATE TEMPORARY TABLE articles2 
SELECT max(date) as maxdate, author_id 
FROM articles 
GROUP BY author_id; 

SELECT authors.name, authors.seo, articles.seo, articles.title FROM articles JOIN articles2 ON (articles2.author_id = articles.author_id AND articles2.maxdate = articles.date) JOIN authors on authors.id = articles.author_id WHERE authors.status = 1 

我希望這可以幫助別人。

+0

如果您使用子查詢,則可以在沒有臨時表的情況下執行此操作。 – Joshmaker

1

不知道你的表結構是什麼,但如果這是我設想的N,則做到這一點:

SELECT author.name, article.title FROM 
    author LEFT JOIN article ON author.id = article.author_id 
    GROUP BY author.id 
    ORDER BY author.id, article.date DESC 
+0

這不會返回最近的文章,而是會爲每位作者獲取第一篇文章,並根據返回的文章對結果進行排序。 – yasar

+0

@ yasar11732,你是對的!我已經更新了我的答案 – Mikhail

+0

仍似乎沒有工作 – yasar

0

我會做這樣的事情,但是如果你發佈的數據庫結構,我會更具體

SELECT * 
    FROM articles,authors 
    WHERE articles.aut = authors.aut 
    GROUP BY authors.aut 
    ORDER BY articles.date DESC 
+1

使用隱式連接的可靠的錯誤形式 - 請參閱http://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins中的第二個答案 –