Get all the rows referencing (via foreign keys) a particular row in a table

前端 未结 3 1777
你的背包
你的背包 2021-01-04 06:14

This seems so simple, but I haven\'t been able to find an answer to this question.

What do I want? A master table with rows that delete themselves w

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 06:36

    SELECT * 
    FROM master ma
    WHERE EXISTS (
        SELECT *
        FROM other ot
        WHERE ot.master_id = ma.id
        );
    

    Or, the other way round:

    SELECT * 
    FROM other ot
    WHERE EXISTS (
        SELECT *    
        FROM master ma
        WHERE ot.master_id = ma.id
        );
    

    SO if you want to update (or delete) only the rows in master that are not referenced by other, you could:

    UPDATE master ma
    SET id = 1000+id
      , name = 'blue'
    WHERE name = 'green'
    AND NOT EXISTS (
        SELECT *
        FROM other ot
        WHERE ot.master_id = ma.id
        );
    

提交回复
热议问题