[英]Update multiple rows with one query
How can I update hundreds of rows at once? 如何一次更新数百行?
Like: UPDATE table SET a = ? WHERE b = ? AND c = 1
喜欢:
UPDATE table SET a = ? WHERE b = ? AND c = 1
UPDATE table SET a = ? WHERE b = ? AND c = 1
but for many rows. 但对于许多行。 The
?
的
?
parameters are arrays... 参数是数组......
I read this answer but it uses CASE and I don't think I can do that... 我读了这个答案,但它使用CASE而我认为我不能这样做......
Right now I have something like this: 现在我有这样的事情:
foreach($values as $key => $value)
$res = $pdo->prepare('UPDATE table SET a = ? WHERE b = ? AND c = 1');
$res->execute(array($value, $key));
}
To do it in a single run of a query, you'd need to use a CASE
and assemble the parameters programmatically . 要在一次查询运行中执行此操作,您需要使用
CASE
并以编程方式组装参数 。 SQL doesn't support variadic prepared statements, and only simple values can be parameterized. SQL不支持可变参数预处理语句,只能参数化简单值 。
Alternatively, define a statement to only take data for one row at a time and run the query in a loop. 或者,定义一个语句,一次只获取一行数据,然后循环运行查询。 Repeated execution is how prepared statements are designed to be used for cases like this.
重复执行是指如何将准备语句设计用于此类情况。
try {
$query = $db->prepare('UPDATE table SET a = ? WHERE b = ? AND c = 1');
foreach ($as as $i => $a) {
$query->execute(array($a, $bs[$i]));
}
} catch (PDOException $e) {
...
}
Use the CASE method as described in the link you provided, but build the query dynamically with the values you want. 使用您提供的链接中描述的CASE方法,但使用您想要的值动态构建查询。
Likely, this will be built with a for loop similar to how you're already doing it, but you will end up with a single query rather than querying your database every iteration. 可能,这将使用类似于您已经执行过的for循环构建,但是您将最终使用单个查询而不是每次迭代查询数据库。
Another way would be to insert your key value pairs (all at once) into a temporary table then do something like this: 另一种方法是将键值对(一次性全部)插入临时表,然后执行以下操作:
UPDATE table t
SET t.a = (SELECT p.a FROM tmp p WHERE p.b = t.b)
WHERE t.b IN (SELECT p.b FROM tmp p) AND t.c = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.