3

我正在尝试从两个使用 ORDER BY DESC 和 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

显然以上方法不起作用,因为 mysql 不接受 order by 并限制使用内部连接。

表结构如下:

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
4

1 回答 1

5

使用针对子选择的 JOIN 来从 my_rel_table 中获取最高 id

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

没有直接测试,因为我没有测试数据!

编辑 - 几次尝试进入前 5 名,但再次没有经过测试

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

或者另一种方式。

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
于 2013-06-27T13:18:37.153 回答