除非在另一个表中引用行,否则从一个表中删除

时间:2017-03-29 15:42:48

标签: sql postgresql

我们有两个表,看起来像这样:

CREATE TABLE devices(
    "id" serial NOT NULL PRIMARY KEY,
    "name" varchar(255) NOT NULL,
    "last_log_id" integer NULL
);

CREATE TABLE log(
    "id" serial NOT NULL PRIMARY KEY, 
    "created_at" timestamp with time zone NOT NULL,
    "msg" varchar(255) NOT NULL,
);

ALTER TABLE "devices" ADD CONSTRAINT 
   "device_last_log_id" FOREIGN KEY ("last_log_id") 
   REFERENCES "log" ("id") DEFERRABLE INITIALLY DEFERRED;

删除所有早于某个“created_at”日期的“日志”行的高效查询是什么,除非它们被“devices”表“last_log_id”列引用?

1 个答案:

答案 0 :(得分:2)

delete from log l
where l.created_at < 'somedate'
and not exists (select 1
     from devices d
     where d.last_log_id = l.id
    );