删除一个表中未被另一个表引用的所有行

时间:2013-10-23 15:15:44

标签: mysql sql

我有两张桌子:

CREATE TABLE  "status" (
    "id" integer NOT NULL PRIMARY KEY,
    "created_at" datetime NOT NULL,    
    "updated_at" datetime NOT NULL);


CREATE TABLE "device" (
    "id" integer NOT NULL PRIMARY KEY,
    "created_at" datetime NOT NULL,
    "updated_at" datetime NOT NULL,
    "last_status_object_id" integer REFERENCES "status" ("id"));

在表“device”中,last_status_object_id引用status.id。

我想删除“last_status_object_id”未引用的所有状态行。我似乎无法弄清楚如何实现这一目标。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:4)

DELETE
    status
FROM
    status
    LEFT JOIN device ON (status.id = last_status_object_id)
WHERE
    device.id IS NULL

答案 1 :(得分:2)

delete from status
where id not in (select last_status_object_id
                            from device);

我们转到sqlfiddle

中的演示

答案 2 :(得分:1)

  

我想删除“last_status_object_id”未引用的所有状态行。

表达方式的一种简单方法是使用NOT EXISTS

DELETE FROM 
    status
WHERE
    NOT EXISTS (SELECT * FROM device WHERE last_status_object_id = status.id)