2

I have two tables:

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"));

In the table "device", last_status_object_id references status.id.

I want to delete all status rows that are not referenced by "last_status_object_id". I can't seem to figure out how to make this happen. Can anyone help me out?

synic
  • 26,359
  • 20
  • 111
  • 149
  • Are you really using mysql - the quotes are invalid (they should be backticks, probably) – AD7six Oct 23 '13 at 15:27
  • 1
    @AD7six souble quotes are not invalid. They are ANSI standard and depending on the MySQL settings, they work there, too. See **[ANSI_QUOTES](http://dev.mysql.com/doc/refman/5.5/en/server-sql-mode.html#sqlmode_ansi_quotes)** – ypercubeᵀᴹ Oct 23 '13 at 15:28
  • @AD7six Sorry, not trying to confuse or mislead anyone. This is the default django output sql. – synic Oct 23 '13 at 15:36
  • You live and learn, me in this case (mysql has a setting for ansi quotes, django uses it) =) – AD7six Oct 23 '13 at 15:42
  • Are you looking from something like [this](http://stackoverflow.com/questions/3384127/delete-sql-rows-where-ids-do-not-have-a-match-in-another-table) – heretolearn Oct 23 '13 at 17:00

3 Answers3

4
DELETE
    status
FROM
    status
    LEFT JOIN device ON (status.id = last_status_object_id)
WHERE
    device.id IS NULL
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
2
delete from status
where id not in (select last_status_object_id
                            from device);

Here we go, with demo in sqlfiddle

mucio
  • 7,014
  • 1
  • 21
  • 33
  • I don't want to delete any device rows. I want to only delete a status row if it's ID is not referenced in device.last_status_object_id – synic Oct 23 '13 at 15:22
  • sorry, copy and past mistake – mucio Oct 23 '13 at 15:24
  • Ok, pretend I didn't add the device_id on status. I'm going to remove it, because it's confusing the question. – synic Oct 23 '13 at 15:26
1

I want to delete all status rows that are not referenced by "last_status_object_id".

An easy way to express that is using NOT EXISTS:

DELETE FROM 
    status
WHERE
    NOT EXISTS (SELECT * FROM device WHERE last_status_object_id = status.id)
AD7six
  • 63,116
  • 12
  • 91
  • 123