问题
I'm trying to delete from two tables which have a relationship using ORDER BY DESC and LIMIT.
DELETE FROM my_rel_table AS t1
LEFT JOIN my_photo_table AS t2 ON t2.typeid = t1.typeid
WHERE t1.relid = 1
AND t1.type = 1
ORDER BY t1.id DESC
LIMIT 1
Obviously the above does not work since mysql does not accept the order by and limit using an inner join.
Table structure is as follows:
my_rel_table
id relid relno typeid type
int int int int tinyint
my_photo_table
typeid pos_x pos_y width height
int int int int int
回答1:
Doing it using a JOIN against a subselect to get the highest id from the my_rel_table
DELETE my_rel_table, my_photo_table
FROM my_rel_table
INNER JOIN
(
SELECT MAX(id) AS MaxId
FROM my_rel_table
WHERE relid = 1
AND type = 1
) Sub1
ON my_rel_table.id = Sub1.MaxId
LEFT OUTER JOIN my_photo_table ON my_photo_table.typeid = my_rel_table.typeid
WHERE my_rel_table.relid = 1
AND my_rel_table.type = 1
Not directly tested as I have no test data!
EDIT - Couple of attempts to do the top 5, but again not tested
DELETE my_rel_table, my_photo_table
FROM my_rel_table
INNER JOIN
(
SELECT id
FROM my_rel_table
WHERE relid = 1
AND type = 1
ORDER BY id DESC
LIMIT 5
) Sub1
ON my_rel_table.id = Sub1.id
LEFT OUTER JOIN my_photo_table ON my_photo_table.typeid = my_rel_table.typeid
WHERE my_rel_table.relid = 1
AND my_rel_table.type = 1
Or a different way.
DELETE my_rel_table, my_photo_table
FROM my_rel_table
INNER JOIN
(
SELECT id, @Counter:=@Counter+1 AS ItemCounter
FROM my_rel_table
CROSS JOIN (SELECT @Counter:=0) Sub1
WHERE relid = 1
AND type = 1
ORDER BY id DESC
) Sub1
ON my_rel_table.id = Sub1.id
AND Sub1.ItemCounter <= 5
LEFT OUTER JOIN my_photo_table ON my_photo_table.typeid = my_rel_table.typeid
WHERE my_rel_table.relid = 1
AND my_rel_table.type = 1
来源:https://stackoverflow.com/questions/17343394/delete-from-multiple-tables-using-order-by-and-limit