在主表中选择在子表中没有连接的行

时间:2013-08-16 09:06:21

标签: sql postgresql

我有两个表:结果(主)和确认(子):

CREATE TABLE result
(
  result_id serial NOT NULL
  CONSTRAINT result_pkey PRIMARY KEY (result_id)
)

CREATE TABLE confirmation
(
  confirmation_id serial NOT NULL,
  result_id integer
  CONSTRAINT confirmation_pkey PRIMARY KEY (confirmation_id),
  CONSTRAINT confirmation_result_id_fkey FOREIGN KEY (result_id)
      REFERENCES result (result_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

我能找到所有确认结果:

SELECT 
result.result_id,
confirmation.confirmation_id
FROM Result
JOIN confirmation ON confirmation.result_id = result.result_id

但我需要反之亦然 - 所有结果仍然没有一次确认。

1 个答案:

答案 0 :(得分:2)

SELECT * FROM result WHERE NOT EXISTS
(SELECT 1 FROM confirmation WHERE confirmation.result_id = result.result_id)