MYSQL 在更新时自动将列实体增加 1?

发布于 2024-10-09 14:12:58 字数 178 浏览 0 评论 0原文

我有一个表: ID,name,count,varchar(255)

现在,我想要的是每次更新表中的行时增加“计数”。

当然,简单的方法是先读取,获取值,在php中加1,然后用新值更新。但!

有什么更快的方法吗? mysql中有没有可以自动执行++的系统?就像自动增量一样,但是对于单个实体本身?

I have a table: ID,name,count,varchar(255)

Now, what i'd like is to increase the "count" each time that row in the table is updated.

Of course, the easy way is to read first, get the value, increase by 1 in php, then update with the new value. BUT!

is there any quicker way to do it? is there a system in mysql that can do the ++ automatically? like autoincrement, but for a single entity on itself?

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

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

发布评论

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

评论(4

孤者何惧 2024-10-16 14:12:58

我看到两个选项:

1.

只需将此逻辑添加到每个更新查询中

UPDATE `table` SET
   `data` = 'new_data',
   `update_counter` = `update_counter` + 1
WHERE `id` = 123

2.

创建一个将自动完成工作的触发器:

CREATE TRIGGER trigger_name
AFTER UPDATE
ON `table`
FOR EACH ROW
    BEGIN
        UPDATE `table`
        SET `update_counter` = `update_counter` + 1
        WHERE `id` = NEW.id
    END

I see two options:

1.

Just add this logic to every update query

UPDATE `table` SET
   `data` = 'new_data',
   `update_counter` = `update_counter` + 1
WHERE `id` = 123

2.

Create a trigger that will do the work automatically:

CREATE TRIGGER trigger_name
AFTER UPDATE
ON `table`
FOR EACH ROW
    BEGIN
        UPDATE `table`
        SET `update_counter` = `update_counter` + 1
        WHERE `id` = NEW.id
    END
谁对谁错谁最难过 2024-10-16 14:12:58

创建触发器:
http://dev.mysql.com/doc/refman/5.1 /en/create-trigger.html

触发器是数据库在某些事件上“触发”的代码片段。就您而言,该事件将是更新。许多 RDBMS 支持触发器,MySQL 也是如此。使用触发器的优点是,更新该实体的每一个 PHP 逻辑都会隐式调用触发器逻辑,当您想从不同的 PHP 逻辑更新实体时,您不必再记住这一点。

Create a trigger:
http://dev.mysql.com/doc/refman/5.1/en/create-trigger.html

Triggers are pieces of code that are "triggered" by the database on certain events. In your case, the event would be an update. Many RDBMS support triggers, so does MySQL. The advantage of using a trigger is that every piece of your PHP logic that updates this entity, will implicitly invoke the trigger logic, you don't have to remember that anymore, when you want to update your entity from a different piece of PHP logic.

送你一个梦 2024-10-16 14:12:58

您可以查看 trigger

或者可以使用额外的 mysql 查询

update table set count=count+1 ;

you can look up at the trigger

or can do with the extra mysql query

update table set count=count+1 ;
堇年纸鸢 2024-10-16 14:12:58
UPDATE table SET name='new value', count=count+1 WHERE id=...

SQL 更新可以使用正在更新的记录中的字段作为更新本身的数据源。

UPDATE table SET name='new value', count=count+1 WHERE id=...

An SQL update can use fields in the record being updated as a source of data for the update itself.

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