How to delete from multiple tables in MySQL?

后端 未结 7 930
温柔的废话
温柔的废话 2020-11-22 07:57

I am trying to delete from a few tables at once. I\'ve done a bit of research, and came up with this

DELETE FROM `pets` p,
            `pets_activities` pa
          


        
7条回答
  •  日久生厌
    2020-11-22 08:41

    Use a JOIN in the DELETE statement.

    DELETE p, pa
          FROM pets p
          JOIN pets_activities pa ON pa.id = p.pet_id
         WHERE p.order > :order
           AND p.pet_id = :pet_id
    

    Alternatively you can use...

    DELETE pa
          FROM pets_activities pa
          JOIN pets p ON pa.id = p.pet_id
     WHERE p.order > :order
       AND p.pet_id = :pet_id
    

    ...to delete only from pets_activities

    See this.

    For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS, NOT EXISTS, IN, NOT IN and etc. But the one above where you specify from which tables to delete with an alias before the FROM clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.

提交回复
热议问题