MySql查询限制和连接语句的排序

时间:2011-11-01 14:04:06

标签: mysql sql foreign-keys

我有两张表作为作者和文章。我想获得每位作者的最新文章列表。我只想为一位作者撰写一篇文章。我希望它是最新的。但是,我甚至无法弄清楚从哪里开始这个SQL查询。

修改

我的表格结构可以像这样简化:

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

3 个答案:

答案 0 :(得分:1)

不知道你的桌面结构是什么,但是如果它是我想象的那么这样做:

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

答案 1 :(得分: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

我希望这有助于某人。

答案 2 :(得分:0)

我会做类似的事情,但如果你发布数据库结构,我会更具体

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