简体   繁体   English

检查记录是否存在的最快方法

[英]Fastest way of checking whether a record exists

What is the fastest way of checking whether a record exists, when I know the primary key? 当我知道主键时,检查记录是否存在的最快方法是什么? select , count , filter , where or something else? selectcountfilterwhere或其他什么东西?

You can check yourself via EXPLAIN QUERY PLAN which will tell you the cost & what it intends to do for a particular query. 您可以通过EXPLAIN QUERY PLAN进行检查,该计划将告诉您费用和对特定查询的打算。

Costs don't directly compare between runs, but you should get a decent idea of whether there are any major differences. 成本不会在运行之间直接进行比较,但是您应该对是否存在主要差异有一个不错的了解。

That being said, I would expect COUNT(id) FROM table WHERE table.id="KEY" is probably the ideal, as it will take advantage of any partial lookup ability (particularly fast in columnar databases like amazon's redshift) and the primary key indexing. 话虽这么说,我希望COUNT(id) FROM table WHERE table.id="KEY"可能是理想的,因为它将利用任何部分查找功能(特别是在诸如亚马逊红移之类的列数据库中快速查找)和主键索引。

When you use count , the database has to continue the search even if it found the record, because a second one might exist. 使用count ,即使找到了记录,数据库也必须继续搜索,因为可能存在第二个记录。 So you should search for the actual record, and tell the database to stop after the first one. 因此,您应该搜索实际记录,并告诉数据库在第一个记录之后停止。

When you ask to return data from the record, then the database has to read that data from the table. 当您要求从记录中返回数据时,数据库必须从表中读取该数据。 But if the record can be found by looking up the ID in an index, that table access would be superfluous. 但是,如果可以通过在索引中查找ID来找到记录,则该表访问将是多余的。 So you should return nothing but the ID you're using to search: 因此,除了用于搜索的ID外,您什么都不应该返回:

SELECT id FROM MyTable WHERE id = ? LIMIT 1;

Anyway, not reading the actual data and the limit are implied when you are using EXISTS, which is simpler in peewee: 无论如何,使用EXISTS时隐含不读取实际数据和限制,这在peewee中更简单:

SELECT EXISTS (SELECT * FROM MyTable WHERE id = ?);
MyTable.select().where(MyTable.id == x).exists()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM