如何构建mySQL查询以根据最大值删除行。
我试过
WHERE jobPositonId = max(jobPostionId)
但是出错了?
答案 0 :(得分:15)
DELETE FROM table ORDER BY jobPositonId DESC LIMIT 1
答案 1 :(得分:12)
使用:
DELETE FROM TABLE t1
JOIN (SELECT MAX(jobPositonId) AS max_id FROM TABLE) t2
WHERE t1.jobPositonId = t2.max_id
请注意, 所有 如果存在重复项,则会删除具有jobPositonId
值的行。
关于1093错误的愚蠢部分是你可以通过在自引用之间放置子查询来绕过它:
DELETE FROM TABLE
WHERE jobPositonId = (SELECT x.id
FROM (SELECT MAX(t.jobPostionId) AS id
FROM TABLE t) x)
MySQL仅在使用UPDATE
& DELETE
语句,如果有正在更新的同一个表的第一级子查询。这就是为什么将它放在二级(或更深)子查询替代工作中的原因。但它只检查子查询 - JOIN语法在逻辑上是等效的,但不会触发错误。
答案 2 :(得分:1)
DELETE FROM `table_name` WHERE jobPositonId = (select max(jobPostionId) from `table_name` limit 1)
OR
DELETE FROM `table_name` WHERE jobPositonId IN (select max(jobPostionId) from `table_name` limit 1)
答案 3 :(得分:0)
这有效:
SELECT @lastid := max(jobPositonId ) from t1;
DELETE from t1 WHERE jobPositonId = @lastid ;
除了两次去数据库之外,这种技术有什么问题吗?