首页 >数据库 >mysql教程 >如何使用 INSERT 和 WHERE 子句在 MySQL 中正确插入或更新数据?

如何使用 INSERT 和 WHERE 子句在 MySQL 中正确插入或更新数据?

Susan Sarandon
Susan Sarandon原创
2025-01-19 06:45:10178浏览

How to Correctly Insert or Update Data in MySQL Using INSERT and WHERE Clauses?

MySQL 数据插入与更新:INSERTWHERE 子句的正确用法

MySQL 的 INSERT 语句不支持 WHERE 子句。因此,以下查询:

<code class="language-sql">INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;</code>

将会失败。

插入新行

如果您尝试插入一个新的 ID 为 1 的行,请使用以下查询:

<code class="language-sql">INSERT INTO Users(id, weight, desiredWeight) VALUES(1, 160, 145);</code>

更新现有行

如果您想更改 ID 为 1 的现有行的 weight/desiredWeight 值,请使用 UPDATE 语句:

<code class="language-sql">UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1;</code>

INSERT ... ON DUPLICATE KEY 语法

您还可以使用 INSERT ... ON DUPLICATE KEY 语法:

<code class="language-sql">INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145;</code>

或者:

<code class="language-sql">INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145;</code>

自增列

如果 id 列是自增列,您可以完全省略 INSERT 查询中的 id 列:

<code class="language-sql">INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 );</code>

MySQL 将自动递增 id 值。

以上是如何使用 INSERT 和 WHERE 子句在 MySQL 中正确插入或更新数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn