Postgresql SQL排除查询



我对Postgresql和SQL一般来说还比较陌生。我已经解决这个问题一段时间了,不知道如何编写查询以获得我想要的结果。

我有这个示例表

付费真[/tr>falsefalse[/tr>
用户 姓名
A aaa true
B bbb
C ccc
D aaa false
E eee

您可以使用不存在,如下所示:

架构:

CREATE TABLE tableUser ("User" varchar(10), Name varchar(10), Paid boolean);

INSERT INTO tableUser  VALUES('A', 'aaa', 'true');
INSERT INTO tableUser  VALUES('B', 'bbb', 'true');
INSERT INTO tableUser  VALUES('C', 'ccc', 'false');
INSERT INTO tableUser  VALUES('D', 'aaa', 'false');
INSERT INTO tableUser  VALUES('E', 'eee', 'false');

查询:

select User, Name, Paid from tableuser t
where paid is false and
not exists (select 1
from tableuser tb
where t.name = tb.name and tb.paid is true );

输出:

user
u_519553787 ccc f
u_519553787

一种方法使用not exists:

select t.*
from t
where not paid and
not exists (select 1
from t t2
where t2.name = t.name and t2.paid
);

当然,外部查询中的not paid是多余的。所以,你可以使用:

select t.*
from t
where not exists (select 1
from t t2
where t2.name = t.name and t2.paid
);

演示:db<gt;小提琴

您可以使用WHERE子查询排除名称:

SELECT
*
FROM mytable
WHERE "Name" NOT IN (                               -- 2
SELECT "Name" FROM mytable WHERE "Paid" = true  -- 1
)
  1. 获取付费记录的所有名称
  2. 获取它们并过滤所有相关记录

最新更新