我正在尝试从表格中最近20个条目的列表中选择5个查看次数最多的文章.我的表结构基本上是这样的:
id | date | title | content | views
我的第一个想法只是使用内部选择来获取最近的20篇文章,然后从中选择,但我还没有运气.
//doesn't work (my version of mysql doesn't support LIMIT in sub queries) $recent = "(SELECT id FROM news ORDER BY date DESC LIMIT 20)"; $result = $db->query("SELECT id, title, date, content FROM news WHERE id IN $recent ORDER BY views DESC LIMIT ".self::RECENT_MAX); //neither does this (syntax error @ 'OFFSET 20') $recent = "(SELECT MAX(date) FROM news ORDER BY date DESC OFFSET 20)"; $result = $db->query("SELECT id, title, date, content FROM news WHERE date > $recent ORDER BY views DESC LIMIT ".self::RECENT_MAX);
任何人都有关于如何构建此查询的任何建议?
我只是测试了它,它的工作原理
SELECT * FROM ( SELECT * FROM news ORDER BY id DESC LIMIT 0, 20 ) lasttwenty ORDER BY views DESC LIMIT 0, 5
服务器版本:5.0.51a-3ubuntu5.4