Reputation: 21522
When I try
DELETE FROM `TreePaths` WHERE `descendant` IN (SELECT `descendant` FROM `TreePaths` WHERE `ancestor`= 0x04);
I get
#1093 - You can't specify target table 'TreePaths' for update in FROM clause
How can I get the delete to work?
update: Table structure:
CREATE TABLE TreePaths (
ancestor VARBINARY(16) NOT NULL,
descendant VARBINARY(16) NOT NULL,
PRIMARY KEY (`ancestor`, `descendant`),
FOREIGN KEY (`ancestor`) REFERENCES Library(iD),
FOREIGN KEY (`descendant`) REFERENCES Library(iD)
);
Table data:
ancestor descendant
01 01
02 02
02 03
03 03
02 04
04 04
02 05
04 05
05 05
02 06
04 06
06 06
07 07
08 08
09 09
10 10
Upvotes: 3
Views: 259
Reputation: 16456
You could create a temporary table to store the descendants:
CREATE TEMPORARY TABLE tmpTable (descendants VARBINARY(16) NOT NULL);
INSERT INTO tmpTable(descendants) (SELECT descendant FROM TreePaths WHERE ancestor = 0x04);
DELETE FROM TreePaths WHERE descendant IN (SELECT descendant from tmpTable);
DROP TABLE tmpTable;
The last line is optional and can be used if you want to free up memory before making something else - temp tables are droped at the end of the session
Upvotes: 0
Reputation: 562601
In MySQL it's easier to do a multi-table delete:
DELETE paths_to_subtree FROM `TreePaths` AS paths_to_subtree
JOIN `TreePaths` AS subtree USING (`descendant`)
WHERE subtree.`ancestor`= 0x04;
Upvotes: 3