Sql 跳过Id列表的第一条插入记录的耗时查询
在postgressql中,我有一个表上有多个articleId列表的数据。无论我在哪里查询,它都应该跳过articleID指定列表中特定用户ID的第一条插入记录Sql 跳过Id列表的第一条插入记录的耗时查询,sql,postgresql,Sql,Postgresql,在postgressql中,我有一个表上有多个articleId列表的数据。无论我在哪里查询,它都应该跳过articleID指定列表中特定用户ID的第一条插入记录 select * from ( select * , row_number() over (partition by articleId order by date) rn from table where articleId in (1200) and userId = 1 ) t where t.rn > 1 它将
select * from (
select * , row_number() over (partition by articleId order by date) rn
from table where articleId in (1200) and userId = 1
) t
where t.rn > 1
它将通过跳过特定userId的每个articleId的第一条插入记录来返回预期的记录。
但如果有大数据,上面的查询将花费更多的时间来执行
表:
身份证件
名称
文章ID
日期
用户ID
1.
abc
1200
2021-05-01 06:09:35
1.
2.
卡介苗
1400
2021-05-02 06:08:35
1.
3.
xyz
1200
2021-05-03 09:09:35
2.
4.
pqr
1200
2021-05-04 08:09:35
1.
5.
xyz
1200
2021-05-05 09:09:35
3.
尝试添加以下索引,该索引应包括对
行号的调用以及WHERE
子句:
在表上创建索引idx(articleId、date、userId);
这将加快您当前的查询速度。像往常一样,在使用EXPLAIN
之前和之后检查执行计划。我建议使用具有正确索引的相关子查询:
select *
from t
where t.articleid = 1200 and t.userId = 1 and
t.date > (select min(t2.date)
from t t2
where t2.articleId = t.articleId
);
然后对于这个查询,您需要两个索引:(articleid,userId)
和(articleid,date)
注意:我有点惊讶,userId
不在partitionby
子句中。因为userId是不同的。查询期望userId=1。哦,我在子查询中丢失了和userId=1
。