遇到了一种情况如下
表大概结构
id-max-all
1— 2—3
前端传来[{“id”=>8,“max”=>“999”},{“id”=>9,“max”=>“1001”}]
需要将前端传来的id中的两个数据更新,将max的值赋给改行的all
这时我想到的是用foreach来遍历数组一条条执行,但是这样做就会执行多句sql,数据少的时候还行多了不就会导致效率极低,我就想一句sql就更新实现
于是我看了这篇博客http://t.zoukankan.com/gaara-zhang-p-10655144.html
//用一句sql完成://#拼接sql//$rs_max结构[{"id"=>8,"max"=>"999"},{"id"=>9,"max"=>"1001"}]$excute = "UPDATE shangpin SET all = CASE id";//#循环拼接$then_ = "";foreach($rs_max as $value){ $then_ = $then_." WHEN ".@$value['id']." THEN ".@$value['max']." ";}$excute = $excute.$then_;$excute = $excute."END";//#循环拼接$ids ="";foreach($rs_max as $value){ $ids = $ids.@$value["id"].",";}//#去除 “,”$ids = @substr($ids,0,@strlen($ids)-1);$excute = $excute." WHERE id IN ($ids)";//这里还能使用问号占位符或者命名占位符将变量代替会更安全,例如://这里只是例子,需要自己去拼接条件,我使用的是thinkphp6的Db类下的execute函数来执行原生sqlDb::execute("update think_user set name=:name where status=:status",['name' => 'thinkphp', 'status' => 1]);//最后生成的sql//UPDATE shangpin SET all = CASE id //WHEN 8 THEN 999 //WHEN 9 THEN 1001 END //WHERE id IN (8,9)
来源地址:https://blog.csdn.net/lemon_xhr/article/details/127267931