根据最大值删除行

发布于 2024-09-17 19:04:40 字数 123 浏览 5 评论 0原文

如何构建 mySQL 查询以根据最大值删除行。

我尝试了

WHERE jobPositonId = max(jobPostionId)

但出现错误?

How can I structure a mySQL query to delete a row based on the max value.

I tried

WHERE jobPositonId = max(jobPostionId)

but got an error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

天煞孤星 2024-09-24 19:04:40
DELETE FROM table ORDER BY jobPositonId DESC LIMIT 1
DELETE FROM table ORDER BY jobPositonId DESC LIMIT 1
诠释孤独 2024-09-24 19:04:40

使用:

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 语法在逻辑上是等效的,但不会触发错误。

Use:

DELETE FROM TABLE t1 
       JOIN (SELECT MAX(jobPositonId) AS max_id FROM TABLE) t2 
 WHERE t1.jobPositonId  = t2.max_id

Mind that all the rows with that jobPositonId value will be removed, if there are duplicates.

The stupid part about the 1093 error is that you can get around it by placing a subquery between the self reference:

DELETE FROM TABLE
 WHERE jobPositonId = (SELECT x.id
                         FROM (SELECT MAX(t.jobPostionId) AS id 
                                 FROM TABLE t) x)

Explanation

MySQL is only checking, when using UPDATE & DELETE statements, if the there's a first level subquery to the same table that is being updated. That's why putting it in a second level (or deeper) subquery alternative works. But it's only checking subqueries - the JOIN syntax is logically equivalent, but doesn't trigger the error.

┊风居住的梦幻卍 2024-09-24 19:04:40
DELETE FROM `table_name` WHERE jobPositonId = (select max(jobPostionId) from `table_name` limit 1)

或者

DELETE FROM `table_name` WHERE jobPositonId IN (select max(jobPostionId) from `table_name` limit 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)
ヤ经典坏疍 2024-09-24 19:04:40

这是可行的:

SELECT @lastid := max(jobPositonId ) from t1; 
DELETE from t1 WHERE jobPositonId = @lastid ; 

除了两次访问数据库之外,这种技术还有什么问题吗?

This works:

SELECT @lastid := max(jobPositonId ) from t1; 
DELETE from t1 WHERE jobPositonId = @lastid ; 

Other than going to the database twice, is there anything wrong with this technique?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文