检查 postgresql 中是否存在一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11274451/
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:35:33  来源:igfitidea点击:

Check if a row exists or not in postgresql

postgresql

提问by Ashwin

I have seen many posts about this in SO. But I could not get an answer. I want to the query to check if a particular row exists or not in a table. If it exists, it should return me a stringtrue and stop the search there itself and if not return false.

我在 SO 中看到了很多关于这个的帖子。但我无法得到答案。我想查询以检查表中是否存在特定行。如果它存在,它应该返回一个字符串true 并在那里停止搜索,如果不存在则返回 false。

回答by Tometzky

select
  case when exists (select true from table_name where table_column=?)
    then 'true'
    else 'false'
  end;

But it would be better to just return boolean instead of string:

但最好只返回布尔值而不是字符串:

select exists (select true from table_name where table_column=?);

回答by wildplasser

Spoiler:

剧透:

-- EXPLAIN ANALYZE
WITH magic AS (
        WITH lousy AS ( SELECT * FROM one  WHERE num = -1)
        SELECT 'True'::text AS truth
        WHERE EXISTS  (SELECT * FROM lousy)
        UNION ALL
        SELECT 'False'::text AS truth
        WHERE NOT EXISTS (SELECT * FROM lousy)
        )
SELECT *
FROM magic
        ;