我有以下代码:
DROP SCHEMA IF EXISTS s CASCADE;
CREATE SCHEMA s;
CREATE TABLE s.t1 (
id1 BigInt,
id2 BigInt,
CONSTRAINT "pk1" PRIMARY KEY (id1)
)
WITH(OIDS=FALSE);
INSERT INTO s.t1 (id1, id2) VALUES (2, 22);
INSERT INTO s.t1 (id1, id2) VALUES (3, 22);
INSERT INTO s.t1 (id1, id2) VALUES (4, 24);
SELECT EXISTS (SELECT TRUE FROM s.t1 t1 WHERE t1.id1 = 2,
SELECT EXISTS (SELECT TRUE FROM s.t1 t1 WHERE t1.id2 = 22);
有没有办法在单个语句中检查多个条件。
我在两个单独的列中寻找值。 我正在寻找的答案是这样的:
bool | bool
------+------
t | t
(1 row)
我得到了解决方案:
SELECT EXISTS(SELECT TRUE FROM s.t1 t1 WHERE t1.id1 = 6),
EXISTS(SELECT TRUE FROM s.t1 t1 WHERE t1.id2 = 22);
输出:
exists | exists
--------+--------
f | t
(1 row)
答案 0 :(得分:2)
怎么样?
SELECT max(x.t2) as t2,
max(x.t22) as t22
FROM ((SELECT t1.id1 as t2, null as t22 FROM s.t1 t1 WHERE t1.id1 = 2)
UNION
(SELECT null as t2, t1.id2 as t22 FROM s.t1 t1 WHERE t1.id2 = 22)) as x;
答案 1 :(得分:0)
SELECT max( case when id1=2 then 'EXISTS' ELSE 'DOESN''T EXISTS' end) id1_2,
max( case when id2=22 then 'EXISTS' ELSE 'DOESN''T EXISTS' end) id2_22,
max( case when id2=33 then 'EXISTS' ELSE 'DOESN''T EXISTS' end) id2_33
FROM s.t1
演示:http://sqlfiddle.com/#!17/85c47/11
| id1_2 | id2_22 | id2_33 |
|--------|--------|----------------|
| EXISTS | EXISTS | DOESN'T EXISTS |
答案 2 :(得分:0)
EXISTS产生一个布尔值,您可以直接使用它:
SELECT
EXISTS (SELECT * FROM s.t1 x1
WHERE x1.id1 = 2) AS ex1
, EXISTS (SELECT * FROM s.t1 x2
WHERE x2.id2 = 22) AS ex2
;