用字符串替换函数replace
update 表名 set 字段名 = replace(字段名,'http://zencart.me','zencart.me')
replace(url, 'aaa', 'bbb') 【将url字段中的aaa批量更改为bbb】
//拓展
正则替换 locate:
LOCATE(substr,str)
POSITION(substr IN str)
返回子串 substr 在字符串 str 中第一次出现的位置,如果子串 substr 在 str 中不存在,返回值为 0:
substring
SUBSTR(str,pos,len): 由中的第位置开始,选出接下去的个字元.
例子:
我要将一张表的字段批量改成另一个字段的值 , b 的值 修改为 a 的值
Db::execute("update `test1` set `b` = replace(b, 0, a) where id in (1,2,3)");
运行后的结果:
把字段改成另外张表的值:
Db::execute("update `test1` set `b` = (select `c` from `test2` where test2.glid = test1.id) where id in (1,2,3)");
//网上找的一种方法(批量更新的sql语句)
UPDATE newhouse_clicks
SET clicks = CASE id
WHEN 1 THEN 1000
WHEN 2 THEN 2000
WHEN 3 THEN 3000
END
WHERE id IN (1,2,3)
更新newhouse_clicks数据表中的clicks字段,当id=1是设置值为1000,当id=2时设置值为2000,当id=3时设置值为3000
更新多个字段
UPDATE newhouse_clicks
SET clicks = CASE id
WHEN 1 THEN 1000
WHEN 2 THEN 2000
WHEN 3 THEN 3000
END,
type = CASE id
WHEN 1 THEN 1
WHEN 2 THEN 6
WHEN 3 THEN 8
END
WHERE id IN (1,2,3)
这条sql语句的含义就是更新newhouse_clicks数据表中的clicks字段,当id=1是设置值为1000,当id=2时设置值为2000,当id=3时设置值为3000,更新type字段,当id=1时更新为type字段为1,当id=2时更新type字段为6,当id=3时,更新type字段为8。
拼出SQL语句
//查询数据库返回的数据格式
$newhouse_clicks = array(
1 => 2,
2 => 3,
3 => 8,
4 => 9,
);
$ids = implode(',', array_keys($newhouse_clicks ));
$sql = "UPDATE newhouse_clicks SET clicks = CASE id ";
foreach ( $newhouse_clicks as $key => $value) {
$sql .= sprintf("WHEN %d THEN %d ", $key, $value);
}
$sql .= "END WHERE id IN ($ids)";
echo $sql;
例子:数据库查询的数据
//查询数据库返回的数据格式
$newhouse_clicks = array(
1 => array('clicks'=>1,'type'=>1,'update_time'=>time()),
2 => array('clicks'=>2,'type'=>2,'update_time'=>time()),
3 => array('clicks'=>3,'type'=>3,'update_time'=>time()),
4 => array('clicks'=>4,'type'=>4,'update_time'=>time()),
);
?>
<?php
//查询数据库返回的数据格式
$newhouse_clicks = array(
1 => array('clicks'=>1,'type'=>1,'update_time'=>time()),
2 => array('clicks'=>2,'type'=>2,'update_time'=>time()),
3 => array('clicks'=>3,'type'=>3,'update_time'=>time()),
4 => array('clicks'=>4,'type'=>4,'update_time'=>time()),
);
//获取所有的id
$newhouse_clicks_keys = array_keys($newhouse_clicks);
//拼接批量更新sql语句
$sql = "UPDATE newhouse_clicks SET ";
//合成sql语句
foreach ($newhouse_clicks[1] as $key => $value) {
$sql .= "{$key} = CASE id ";
foreach ($newhouse_clicks as $newhouse_clicks_key=>$newhouse_clicks_value) {
$sql .= sprintf("WHEN %d THEN %d ", $newhouse_clicks_key, $newhouse_clicks_value[$key]);
}
$sql .= "END, ";
}
//把最后一个,去掉
$sql = substr($sql, 0, strrpos($sql,','));
//合并所有id
$ids = implode(',', $newhouse_clicks_keys);
//拼接sql
$sql .= " WHERE ID IN ({$ids})";
echo $sql;