Delete from multiple tables using order by and limit

大兔子大兔子 提交于 2021-01-28 02:50:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!