Delete, Update with derived tables?

后端 未结 2 1295
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 05:52

I have just studied FROM clause and derived tables in mysql and most of the websites provided the examples using SELECT command

<
2条回答
  •  时光说笑
    2021-01-20 06:25

    You can't directly delete from the subquery, but you can still use it if you'd like, you'll just need to use it in a JOIN:

    DELETE usrs
    FROM usrs
        INNER JOIN (
            SELECT * FROM usrs WHERE name = 'john'
        ) t ON usrs.Id = t.Id
    

    Or you could use IN:

    DELETE usrs
    WHERE ID IN (
       SELECT ID
       FROM usrs
       WHERE name = 'John'
    )
    

    With this said, for this example, I don't know why you'd want a subquery:

    DELETE usrs WHERE name = 'John'
    

    Edit base on comments. To delete from multiple tables at the same time, you can either have multiple DELETE statements, or you can use something like the following:

    delete t1, t2, t3
    from (select 'john' as usr) t
      left join t1 on t.usr=t1.usr
      left join t2 on t.usr=t2.usr
      left join t3 on t.usr=t3.usr
    
    • SQL Fiddle Demo

提交回复
热议问题