2011-11-01 41 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中的第二个答案 –