Remove rows NOT referenced by a foreign key

前端 未结 2 1271
悲哀的现实
悲哀的现实 2021-02-09 11:42

This is somewhat related to this question:

I have a table with a primary key, and I have several tables that reference that primary key (using foreign keys). I need to

相关标签:
2条回答
  • 2021-02-09 12:19

    At the heart of it, SQL servers don't maintain 2-way info for constraints, so your only option is to do what the server would do internally if you were to delete the row: check every other table.

    If (and be damn sure first) your constraints are simple checks and don't carry any "on delete cascade" type statements, you can attempt to delete everything from your group table. Any row that does delete would thus have nothing reference it. Otherwise, you're stuck with Quassnoi's answer.

    0 讨论(0)
  • 2021-02-09 12:24
    DELETE
    FROM    group g
    WHERE   NOT EXISTS
            (
            SELECT  NULL
            FROM    table1 t1
            WHERE   t1.groupid = g.groupid
            UNION ALL
            SELECT  NULL
            FROM    table1 t2
            WHERE   t2.groupid = g.groupid
            UNION ALL
            …
            )
    
    0 讨论(0)
提交回复
热议问题