I have just studied FROM
clause and derived tables
in mysql and most of the websites provided the examples using SELECT
command
Derived tables exist only for the duration of the parent query they're a member of. Assuming that this syntax and the operations were allowed by MySQL, consider what happens:
a) Your main query starts executing
b) the sub-query executes and returns its results as a temporary table
c) the parent update changes that temporary table
d) the parent query finishes
e) temporary tables are cleaned up and deleted
Essentially you'll have done nothing except waste a bunch of cpu cycles and disk bandwidth.
UPDATE
queries DO allow you to join against other tables to use in the WHERE
clause, e.g..
UPDATE maintable
LEFT JOIN othertable ON maintable.pk = othertable.fk
SET maintable.somefield='foo'
WHERE othertable.otherfield = 'bar'
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