MySql Query: Select top 3 rows from table for each category(MySql 查询:从表中为每个类别选择前 3 行)
问题描述
我有一个包含记录的表,其中有一行名为 category.我插入了太多文章,我只想从每个类别中选择两篇文章.
I have a table with records and it has a row called category. I have inserted too many articles and I want to select only two articles from each category.
我试图做这样的事情:
我创建了一个视图:
CREATE VIEW limitrows AS
SELECT * FROM tbl_artikujt ORDER BY articleid DESC LIMIT 2
然后我创建了这个查询:
Then I created this query:
SELECT *
FROM tbl_artikujt
WHERE
artikullid IN
(
SELECT artikullid
FROM limitrows
ORDER BY category DESC
)
ORDER BY category DESC;
但这不起作用并且只给我两条记录?
But this is not working and is giving me only two records?
推荐答案
LIMIT 只停止语句返回的结果数.您正在寻找的通常称为分析/窗口/排名函数 - MySQL 不支持,但您可以使用变量进行模拟:
LIMIT only stops the number of results the statement returns. What you're looking for is generally called analytic/windowing/ranking functions - which MySQL doesn't support but you can emulate using variables:
SELECT x.*
FROM (SELECT t.*,
CASE
WHEN @category != t.category THEN @rownum := 1
ELSE @rownum := @rownum + 1
END AS rank,
@category := t.category AS var_category
FROM TBL_ARTIKUJT t
JOIN (SELECT @rownum := NULL, @category := '') r
ORDER BY t.category) x
WHERE x.rank <= 3
如果您不更改 SELECT x.*,结果集将包括 rank 和 var_category 值 - 您将拥有如果不是这种情况,请指定您真正想要的列.
If you don't change SELECT x.*, the result set will include the rank and var_category values - you'll have to specify the columns you really want if this isn't the case.
这篇关于MySql 查询:从表中为每个类别选择前 3 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySql 查询:从表中为每个类别选择前 3 行
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
