MySQL UPDATE - 选择性更新

发布于 2024-09-16 22:48:14 字数 767 浏览 5 评论 0原文

首先,对这个糟糕的标题表示歉意,我想不出更好的方式来阐明我的问题。 (随意建议更好的替代方案)

基本上我有一个带有“计数”列的表。 我想将除具有最高值的 10 行之外的所有计数重置为零。我希望将它们重置为 0。

如何在不编写多个查询的情况下实现此目的?

更新 我的查询如下,现在

UPDATE covers AS t1 
  LEFT JOIN (SELECT t.cover_id 
               FROM covers t 
               ORDER BY t.cover_views DESC 
               LIMIT 10) AS t2 ON t2.id = t.id
   SET cover_views = 0
   WHERE t2.id IS NULL

收到错误 #1054 - “where 子句”中的未知列“t2.id” - 知道为什么吗?

我也尝试了以下方法,结果相同

UPDATE covers t1 
  LEFT JOIN (SELECT t.cover_id 
               FROM covers t 
               ORDER BY t.cover_views DESC 
               LIMIT 10) t2 ON t2.id = t.id
   SET t1.cover_views = 0
   WHERE t2.id IS NULL

First up, apologies for the awful title I couldn't think of a better way to articulate my issue. (Feel free to suggest better altnernatives)

Basically I have a table with a "count" column.
I want to reset all counts to zero except for the 10 rows with the top values. I want them to be reset to 0.

How do I achieve this without writing multiple queries?

Update
I have my query as the following now

UPDATE covers AS t1 
  LEFT JOIN (SELECT t.cover_id 
               FROM covers t 
               ORDER BY t.cover_views DESC 
               LIMIT 10) AS t2 ON t2.id = t.id
   SET cover_views = 0
   WHERE t2.id IS NULL

I get the error #1054 - Unknown column 't2.id' in 'where clause' - any idea why?

I also tried the following with the same result

UPDATE covers t1 
  LEFT JOIN (SELECT t.cover_id 
               FROM covers t 
               ORDER BY t.cover_views DESC 
               LIMIT 10) t2 ON t2.id = t.id
   SET t1.cover_views = 0
   WHERE t2.id IS NULL

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

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

发布评论

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

评论(3

好倦 2024-09-23 22:48:14

使用:

UPDATE TABLE t1 
  LEFT JOIN (SELECT t.id 
               FROM TABLE t 
           ORDER BY t.id DESC 
              LIMIT 10) t2 ON t2.id = t1.id
   SET TABLE.count = 0
 WHERE t2.id IS NULL

Use:

UPDATE TABLE t1 
  LEFT JOIN (SELECT t.id 
               FROM TABLE t 
           ORDER BY t.id DESC 
              LIMIT 10) t2 ON t2.id = t1.id
   SET TABLE.count = 0
 WHERE t2.id IS NULL
舟遥客 2024-09-23 22:48:14

尝试:

update <table> t 
left outer join 
(
select id from <table> order by <counter> desc limit 10
) c on c.id = t.id 
set 
 <counter> = 0
where 
 c.id is null;

try:

update <table> t 
left outer join 
(
select id from <table> order by <counter> desc limit 10
) c on c.id = t.id 
set 
 <counter> = 0
where 
 c.id is null;
离笑几人歌 2024-09-23 22:48:14

您可以使用子查询:

update A set count = 0 where A.id not in 
(select id from A order by count desc limit 10)

You can use a subquery:

update A set count = 0 where A.id not in 
(select id from A order by count desc limit 10)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文