简体   繁体   English

SQL 查看“ANY”行是否符合条件

[英]SQL to see if 'ANY' rows match the criteria

given the following SQL in Postgres, I want to see if any row matches the criteria and not interested in what rows match.鉴于 Postgres 中的以下 SQL ,我想查看是否有任何行与条件匹配,并且匹配的行不感兴趣。 eg in this case, (if i have any perishable stock)例如在这种情况下,(如果我有任何易腐烂的库存)

The only way i have achieved this is use the limit clause but its very slow (there is >100,000,000 records)我实现这一目标的唯一方法是使用限制子句,但它非常慢(有 >100,000,000 条记录)

select is_perishable
from stock
where is_perishable = true
limit 1;

Is there a quicker, more eloquent method in achieving this?是否有更快、更多的 eloquent 方法来实现这一目标?

You could try EXISTS:你可以试试 EXISTS:

SELECT EXISTS(
  select null from stock where is_perishable = true
)

How much faster it'll be, if at all, I've no idea, but it ought to be optimized to quit early upon assessing the presence of a record.. Though so would a limit query... If it's no different, post the query plan如果有的话,它会快多少,我不知道,但应该优化它以在评估记录的存在时尽早退出。虽然限制查询也会如此......如果没有什么不同,发布查询计划

this might be a little bit faster:这可能会快一点:

select 1
from stock
where is_perishable = true
limit 1;

nevertheless it can be slow if there is no row with is_perishable = true.但是,如果没有 is_perishable = true 的行,它可能会很慢。 here a proper index can be helpful.在这里,适当的索引可能会有所帮助。

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

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