为每个类别选择 N 条记录并按 X 排序
我有一个包含博客文章的数据库表。我想在主页上显示每个类别的一篇(或多篇)帖子,例如按日期排序。
所以我的帖子表如下所示:id |标题 |描述 |猫 |文件名 | date
我将如何创建这样的查询?我想过使用 group-by 或子选择,但我不确定这对性能是否有好处......该表有大量记录。
I have a database table that contains blog posts. I want to show on the homepage one (or more) post for each category, ordering by date, for example.
So my posts table looks like this: id | title | description | cat | filename | date
How would I create such a query? I've thought to use group-by or a subselect but I'm not sure if it's a good thing for performance... the table has a large number of records.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MySQL 不支持分析函数(ROW_NUMBER、RANK、DENSE_RANK、NTILE...),但您可以使用变量来模拟该功能。
如果您想要 N 个最新博客文章:
如果您希望排名 1 的博客文章成为最早的博客文章,请将 ORDER BY 更改为:
MySQL doesn't support analytic functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE...), but you can emulate the functionality with variables.
If you want the N most recent blog posts:
If you want rank of 1 to be the earliest blog post, change the ORDER BY to:
使用更现代的 SQL,使用 CTE 和 Windows 函数(在 PostgreSQL 9.3 中测试,但我怀疑它也适用于最新版本的 MySQL),以显示每个类别 2 个标题:
With more modern SQL, using CTE and Windows Functions (tested in PostgreSQL 9.3, but I suspect it'll work on a recent version of MySQL too), to show say 2 title per category: