MySQL實現一條sql完成多條數據的更新
阿新 • • 發佈:2018-06-27
turn update col || param 格式 IT post href 原始功能:
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 $data array 待更新的數據,二維數組格式 * @param array $params array 值相同的條件,鍵值對應的一維數組 * @param string $field string 值不同的條件,默認為id * @return bool|string */ function batchUpdate($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", ‘post‘, $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‘
參考文章:
PHP批量更新
MySQL實現一條sql完成多條數據的更新