检查是否存在对应于另一列的特定列值以及 return 它在 sql 中的 ID

check if a specific column value exists corresponding to another column and return its id in sql

有个table说t1

id subject day event
211 maths mon asmnt
222 maths tue asmnt
223 science mon test
224 science tue asmt
225 science wed insp
226 computers mon asmt
227 maths mon test
228 computers mon insp
229 computers thr asmnt
230 computers fri asmnt

现在我想要一个 SQL 查询 来查找 从来没有 在任何一天 event = test 的 id 主题和 return 它的第一个事件 所以输出是

id subject day event
226 computers mon asmt

use not exists and row_number() 但对于 postgre 来说,使用 distinct 是明智的,@Tim

已经给出了答案
 with cte as 
(  select t1.*,
  row_number()over(partition by subject order by id)
  rn from table_name t1
    where not exists ( select 1 from table_name t2 where t1.subject=t2.subject
                                and t2.event='test')  
) select * from cte where rn=1

您可以使用 NOT INnot exists 来排除存在 event='test' 的主题。将 order Limit 1 与 order by id 一起使用将 select 一行具有 id 列的最低值。

架构和插入语句:

 create table t1 (id    int,subject varchar(20), day varchar(20), event varchar(20));

 insert into t1 values(211, 'maths' ,'mon', 'asmnt');
 insert into t1 values(222, 'maths' ,'tue', 'asmnt');
 insert into t1 values(223, 'science'   ,'mon', 'test');
 insert into t1 values(224, 'science'   ,'tue', 'asmt');
 insert into t1 values(225, 'science'   ,'wed', 'insp');
 insert into t1 values(226, 'computers' ,'mon', 'asmt');
 insert into t1 values(227, 'maths' ,'mon', 'test');
 insert into t1 values(228, 'computers' ,'mon', 'insp');
 insert into t1 values(229, 'computers' ,'thr', 'asmnt');
 insert into t1 values(230, 'computers' ,'fri', 'asmnt');

查询 1:使用 NOT IN

 SELECT * FROM t1 a
 WHERE subject not in
                 (
                   SELECT subject FROM t1 b WHERE b.event='test'
                 )
 order by id
 Limit 1

输出:

id subject day event
226 computers mon asmt

查询 2:使用 not exists

 SELECT * FROM t1 a
 WHERE not exists 
                 (
                   SELECT 1 FROM t1 b WHERE b.event='test' and a.subject=b.subject
                 )
 order by id
 Limit 1

输出:

id subject day event
226 computers mon asmt

db<>fiddle here

我们可以在这里使用 DISTINCT ON 以及现有的逻辑:

SELECT DISTINCT ON (subject) *
FROM t1 a
WHERE NOT EXISTS (SELECT 1 FROM t1 b
                  WHERE b.subject = a.subject AND b.event = 'test')
ORDER BY subject, id;