Mysql - LEFT JOIN - 获得第一个条目

时间:2014-08-17 06:55:58

标签: mysql left-join greatest-n-per-group

我在MySql中有这个结构

tables

我想得到:

第一篇帖子,来自最后一个主题WHERE类别是'新闻'

在此示例中,它是来自帖子的行,其中id = 2,如图像

上所标记

row

到目前为止,我收到了这个问题:

SELECT *
FROM forum_post AS p 
LEFT JOIN forum_topic AS t ON p.topic_id = t.id
LEFT JOIN forum_category AS c ON t.category_id = c.id
WHERE c.title = 'News' AND t.id = MAX(t.id)
ORDER BY p.id ASC LIMIT 1

编辑:

肮脏的解决方案:

SELECT * FROM forum_post
WHERE topic_id = (SELECT MAX(id) FROM forum_topic WHERE category_id = 1)
ORDER BY id ASC LIMIT 1

3 个答案:

答案 0 :(得分:1)

您仍然可以使用连接查询而不是子查询来获取类别的最后一个主题的第一个帖子,请注意,连接中的子查询只运行一次以获取结果集,在您的情况下,子查询将针对每次迭代运行

SELECT * FROM
forum_post AS p 
  JOIN 
    (SELECT 
      t.id 
    FROM
      forum_topic AS t 
      JOIN forum_category AS c 
        ON t.category_id = c.id 
    WHERE c.title = 'News' 
    ORDER BY t.id DESC 
    LIMIT 1) t
  ON p.topic_id = t.id 
ORDER BY p.id ASC 
LIMIT 1 

答案 1 :(得分:0)

select fp.* from forum_post fp,
(select min(fp.id) from forum_post fp where topic_id in 
 (select max(ft.id) from forum_topic ft inner join forum_category fc 
     on fc.id = ft.category_id where fc.title = 'News'))T 
where fp.id = T.id

[如果没有forum_posts,则不会返回任何行]

编辑: 更新[虽然我还没有尝试过执行]

答案 2 :(得分:0)

我还没有测试过,但它应该是这样的:

SELECT fm.remply
FROM forum_topic ft
JOIN forum_category fc
    ON ft.category_id = fc.category_id
    AND fc.title = 'News'
JOIN forum_post fm
    ON ft.id = fm.topic_id
ORDER BY ft.id DESC
        ,fm.id DESC
LIMIT 1