使用条件更新查询?
我不确定这是否可能。如果没有,请告诉我。
我有一个更新 3 个字段的 PDO mysql。
$update = $mypdo->prepare("UPDATE tablename SET field1=:field1,
field2=:field2,
field3=:field3
WHERE key=:key");
但我希望仅当 $update3 = true;
时才更新 field3
(意味着 field3
的更新是由条件语句控制的)
是这可以通过单个查询来完成吗?
我可以使用 2 个查询来完成此操作,其中更新 field1
和 field2
,然后检查布尔值,并根据需要在单独的查询中更新 field3
。
//run this query to update only fields 1 and 2
$update_part1 = $mypdo->prepare("UPDATE tablename SET field1=:field1,
field2=:field2
WHERE key=:key");
//if field3 should be update, run a separate query to update it separately
if ($update3){
$update_part2 = $mypdo->prepare("UPDATE tablename SET field3=:field3
WHERE key=:key");
}
但希望有一种方法可以在一次查询中完成此任务吗?
I'm not sure if this possible. If not, let me know.
I have a PDO mysql that updates 3 fields.
$update = $mypdo->prepare("UPDATE tablename SET field1=:field1,
field2=:field2,
field3=:field3
WHERE key=:key");
But I want field3
to be updated only when $update3 = true;
(meaning that the update of field3
is controlled by a conditional statement)
Is this possible to accomplish with a single query?
I could do it with 2 queries where I update field1
and field2
then check the boolean and update field3
if needed in a separate query.
//run this query to update only fields 1 and 2
$update_part1 = $mypdo->prepare("UPDATE tablename SET field1=:field1,
field2=:field2
WHERE key=:key");
//if field3 should be update, run a separate query to update it separately
if ($update3){
$update_part2 = $mypdo->prepare("UPDATE tablename SET field3=:field3
WHERE key=:key");
}
But hopefully there is a way to accomplish this in 1 query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要进行多次查询。为什么不根据该条件构建查询字符串,然后将其传递给数据库适配器来执行?可以是这样的:
You don't need to do multiple queries. Why don't you just structure your query string based on that conditional, and after that just pass it to your DB adapater for execution ? It could be as follow: