使用 mySQL 更新多行
我有一个如下所示的表:
property propertyid value
active 1 1
datastore 2 apc
我将如何制定 SQL 查询来更新几行,而不更新所有行。 IE,如果有 6 行,更新 2,3 和 4 但不更新 1,5 和 6?
谢谢。
I have a table that look like this:
property propertyid value
active 1 1
datastore 2 apc
How would I formulate a SQL query to update a few rows, without updating all of them. IE, if there were 6 rows, update 2,3 and 4 but not 1,5 and 6?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您要在具有相同值的所有行上更新相同的列,您可以使用这样的查询轻松完成。
这会将值 5 设置为属性 id 为 2,3 或 4 的所有行。
如果您想用不同的值更新不同的行,恐怕您将不得不编写单独的 SQL 语句。您可以使用 CASE 语句进行 SQL 查询但通过简单的 SQL 查询就可以提高可读性和可维护性。
假设您正在从应用程序操作数据库,我非常确定无论您使用什么编程语言,编写 1 个 SQL 语句并循环、替换值并执行查询或附加所有 SQL 更新都会很容易语句到字符串(循环时)并将其传递到数据库以立即执行所有语句。很抱歉,我不知道其中一个是否会对另一个产生重大的性能影响,但我相信一次执行所有操作会对性能产生一些好处。
If it is the same column(s) that you are updating on all the rows with the same value you can do it easily with a query like this.
This will set the value 5 to all rows where the property id is either 2,3 or 4.
If you want to update different rows with different values, I am afraid you will have to write separate SQL statements. You could come with a SQL query using the CASE statement but it would be much readable and maintainable with a simple SQL query.
Assuming that you are manipulating the database from an application, I am pretty sure that with whatever programming language you will be using, it will be easy as writing 1 SQL statement and looping, replacing the values and executing the query OR appending all the SQL update statements to a string (while looping) and pass it to the database to execute all at once. I am sorry I don't know whether either would have a significant performance impact over the other, but I believe that executing all at once would have some benefit in regards to performance.