when I am studying the lectures of database system, I tried the code provided in the lectures slides but was not working. The example is to delete some tuples from a table.
Example:Delete from Beers(name, manf) all beers for which there is another beer by the same manufacturer. And the code provided in the slide is as follows:
DELETE FROM Beers b
WHERE EXISTS(
SELECT name
FROM Beers
WHERE manf = b.manf AND name <> b.name);
I create the Beers table and insert two rows as follows:
create table Beers(
name CHAR(30) primary key,
manf CHAR(30)
);
insert into Beers(name, manf)
values('Bud', 'A-B');
insert into Beers
values('Bud-lite', 'A-B');
and test the code. According to the lecture, it should delete all the tuples in Beers , however, the code is not working and kept showing "you can't specify target table 'Beers' for update in FROM clause. when I run the delete operation on SQL.
Can someone tell me what's wrong with the code? Thanks!
Add note: Just find out MySQL can't run the previous code but can run this one:
Delete from Beers
where exists(
select a.name from(select b.name from Beers b
where manf = b.manf AND name!= b.name) as a);
But I still don't know why we need to use select twice inside exists. Could someone explain how this code works?