postgresql 检查列中是否存在值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8149596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 23:12:14  来源:igfitidea点击:

Check value if exists in column

postgresql

提问by Perlos

I'd like to know how to maximize speed when querying for the presence of a varcharvalue in a column in a specific table. I don't need to know where it is, or how many occurrences there are, I just want a true/false. Of course, the column has an index.

我想知道在查询varchar特定表的列中是否存在值时如何最大限度地提高速度。我不需要知道它在哪里,或者出现了多少次,我只想要一个true/ false。当然,该列有一个索引。

Now, I have this:

现在,我有这个:

SELECT exists (SELECT 1 FROM table WHERE column = <value> LIMIT 1);

回答by Mike Sherrill 'Cat Recall'

EXISTS should normally return as soon as the subquery finds one row that satisfies its WHERE clause. So I think your query is as fast as you can make it.

EXISTS 通常应该在子查询找到满足其 WHERE 子句的行后立即返回。所以我认为您的查询尽可能快。

I was a little surprised that LIMIT 1seems to always speed up the query very slightly. I didn't expect that. You can see the effect with EXPLAIN ANALYZE.

我有点惊讶,这LIMIT 1似乎总是略微加快查询速度。我没想到。你可以看到效果EXPLAIN ANALYZE

EXPLAIN ANALYZE
SELECT exists (SELECT 1 FROM table WHERE column = <value> LIMIT 1);

回答by blindguy

I have had recent success with the following in some cases:

在某些情况下,我最近在以下方面取得了成功:

SELECT count(1) > 0
WHERE column = <value>