原始功能:
update categories SET display_order= 3,title = 'New Title 1' where id=1;
update categories SET display_order= 4,title = 'New Title 2' where id=2;
update categories SET display_order= 5,title = 'New Title 3' where id=3;
功能改进:
UPDATE categories SET
display_order = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END,
title = CASE id
WHEN 1 THEN 'New Title 1'
WHEN 2 THEN 'New Title 2'
WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)
PHP自动生成sql
$data = [
['id' => 1, 'parent_id' => 100, 'title' => 'A', 'sort' => 1],
['id' => 2, 'parent_id' => 100, 'title' => 'A', 'sort' => 3],
['id' => 3, 'parent_id' => 100, 'title' => 'A', 'sort' => 5],
['id' => 4, 'parent_id' => 100, 'title' => 'B', 'sort' => 7],
['id' => 5, 'parent_id' => 101, 'title' => 'A', 'sort' => 9],
];
例如,我们想让parent_id为100、title为A的记录依据不同id批量更新:
/**
* 批量更新函数
* @param $tableName 表名
* @param $data array 待更新的数据,二维数组格式
* @param array $params array 值相同的条件,键值对应的一维数组
* @param string $field string 值不同的条件,默认为id
* @return bool|string
*/
function batchUpdate($tableName,$data, $field, $params = [])
{
if (!is_array($data) || !$field || !is_array($params)) {
return false;
}
$updates = parseUpdate($data, $field);
$where = parseParams($params);
// 获取所有键名为$field列的值,值两边加上单引号,保存在$fields数组中
// array_column()函数需要PHP5.5.0+,如果小于这个版本,可以自己实现,
// 参考地址:http://php.net/manual/zh/function.array-column.php#118831
$fields = array_column($data, $field);
$fields = implode(',', array_map(function($value) {
return "'".$value."'";
}, $fields));
$sql = sprintf("UPDATE `%s` SET %s WHERE `%s` IN (%s) %s", $tableName, $updates, $field, $fields, $where);
return $sql;
}
/**
* 将二维数组转换成CASE WHEN THEN的批量更新条件
* @param $data array 二维数组
* @param $field string 列名
* @return string sql语句
*/
function parseUpdate($data, $field)
{
$sql = '';
$keys = array_keys(current($data));
foreach ($keys as $column) {
$sql .= sprintf("`%s` = CASE `%s` \n", $column, $field);
foreach ($data as $line) {
$sql .= sprintf("WHEN '%s' THEN '%s' \n", $line[$field], $line[$column]);
}
$sql .= "END,";
}
return rtrim($sql, ',');
}
/**
* 解析where条件
* @param $params
* @return array|string
*/
function parseParams($params)
{
$where = [];
foreach ($params as $key => $value) {
$where[] = sprintf("`%s` = '%s'", $key, $value);
}
return $where ? ' AND ' . implode(' AND ', $where) : '';
}
调用:
echo batchUpdate($data, 'id', ['parent_id' => 100, 'title' => 'A']);
生成sql
WHEN '1' THEN '1'
WHEN '2' THEN '2'
WHEN '3' THEN '3'
WHEN '4' THEN '4'
WHEN '5' THEN '5'
END,`parent_id` = CASE `id`
WHEN '1' THEN '100'
WHEN '2' THEN '100'
WHEN '3' THEN '100'
WHEN '4' THEN '100'
WHEN '5' THEN '101'
END,`title` = CASE `id`
WHEN '1' THEN 'A'
WHEN '2' THEN 'A'
WHEN '3' THEN 'A'
WHEN '4' THEN 'B'
WHEN '5' THEN 'A'
END,`sort` = CASE `id`
WHEN '1' THEN '1'
WHEN '2' THEN '3'
WHEN '3' THEN '5'
WHEN '4' THEN '7'
WHEN '5' THEN '9'
END WHERE `id` IN ('1','2','3','4','5') AND `parent_id` = '100' AND `title` = 'A'
参考文章: