MYSQL 在更新时自动将列实体增加 1?
我有一个表: 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我看到两个选项:
1.
只需将此逻辑添加到每个更新查询中
2.
创建一个将自动完成工作的触发器:
I see two options:
1.
Just add this logic to every update query
2.
Create a trigger that will do the work automatically:
创建触发器:
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.
您可以查看 trigger
或者可以使用额外的 mysql 查询
you can look up at the trigger
or can do with the extra mysql query
SQL 更新可以使用正在更新的记录中的字段作为更新本身的数据源。
An SQL update can use fields in the record being updated as a source of data for the update itself.