简体   繁体   English

哪个查询更有效? (PostgreSQL)

[英]Which query is more efficient? (Postgresql)

I have a table that will have many records (Millions).我有一张有很多记录(百万)的表。 When one of the ".._ups" values is set to 0, I need to check if all the other "ups" types for that record are also 0, and delete it.当“.._ups”值之一设置为 0 时,我需要检查该记录的所有其他“ups”类型是否也为 0,然后将其删除。 This occurs because a user can cancel their "ups" of a particular type, but not of another type.发生这种情况是因为用户可以取消他们特定类型的“ups”,但不能取消其他类型的“ups”。 If they cancel every type of "up", I want to delete the record.如果他们取消所有类型的“向上”,我想删除记录。

The time_unit field is a time unit that changes every 5 minutes. time_unit字段是每 5 分钟更改一次的时间单位。 So each vote records what time_unit it belongs to.所以每一个投票记录它属于哪个time_unit

Is it more efficient to only search for (delete) votes with that time unit, or search for (delete) all of the votes in the (potentially huge) table?仅搜索(删除)具有该时间单位的投票,还是搜索(删除)(可能很大)表中的所有投票更有效? I plan on indexing time_unit .我计划索引time_unit It's hard for me to test this because I don't have the records yet.我很难测试这个,因为我还没有记录。

Query 1查询 1

DELETE FROM ups 
WHERE time_unit = $tuid AND big_ups = 0 AND sol_ups = 0 AND blue_ups = 0;

or或者

Query 2查询 2

DELETE FROM ups 
WHERE big_ups = 0 AND sol_ups = 0 AND blue_ups = 0;

Your search condition is clear:您的搜索条件很明确:

Delete all rows where all three ups are zero.删除所有三个 ups 都为零的所有行。

You explain the time frame is not important when it comes to deleting the rows.您解释了删除行时时间范围并不重要。 You just want to get rid of rows that match the condition above.您只想删除符合上述条件的行。

Then, the second query is the best one if you happen to have the right index.然后,如果您碰巧有正确的索引,则第二个查询是最好的。 The index you need is:您需要的索引是:

create index ix1 on ups (big_ups, sol_ups, blue_ups);

With that index the deletion should be quite fast since PostgreSQL performs logical deletion on the heap, not a physical one.使用该索引,删除应该非常快,因为 PostgreSQL 在堆上执行逻辑删除,而不是物理删除。

With first query (using time_unit=$tuid when it is indexed) database will go directly to that record (only) just and check if other columns are zero for deletion.使用第一个查询(索引时使用time_unit=$tuid )数据库将 go 直接(仅)到该记录并检查其他列是否为零以进行删除。 In second query database must pass through all records (ful table scan) and look if they there are zeroes in your columns.在第二个查询中,数据库必须通过所有记录(全表扫描)并查看它们是否在您的列中为零。

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

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