19

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

4

2 回答 2

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

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

select exists (select true from table_name where table_column=?);
于 2012-06-30T17:21:56.060 回答
-17

剧透:

-- 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
        ;
于 2012-06-30T13:49:40.337 回答