正常批次更新資料 例如 更新使用者狀態
update user set status = 1;
如果遇到每個人的狀態都不一樣 只能一個一個更新
update user set status = 1 and uid =1 ;
update user set status = 0 and uid =2 ;
...
可用用join方式實現
UPDATE `user` a JOIN
(
SELECT 1 AS id, 1 AS `status`
UNION
SELECT 2 AS id, 0 AS `status`
) b USING(id)
SET a.status=b.status;
php 類實現
<?php
/**
* 批次更新
*
* @author Lin
*/
class UpdateAll {
/**
* 獲取批次更新
* @param string $table 表名
* @param array $where 更新條件 array('id')
* @param array $data 更新資料(包含更新條件的資料)二維陣列
* @return string 獲取更新sql語句
*/
public static function execute($table, $where, $data) {
$sql = self::getSql($table, $where, $data);
if ($sql) {
//自己根據需求完成更新程式碼
}
return $sql;
}
/**
* 獲取批次更新語句
* 原理https://www.cnblogs.com/AaronCui/p/10968893.html
* @param string $table 表名
* @param array $where 更新條件 array('id')
* @param array $data 更新資料(包含更新條件的資料)二維陣列
* @return string 獲取更新sql語句
*/
public static function getSql($table, $where, $data) {
if (empty($table) || empty($where) || empty($data) || !is_array($where) || !is_array($data)) {
return false;
}
$where_string = self::where($where);
$update = self::update($data);
$set = self::set($where, $data);
if (!$update || !$set || !$where) {
return false;
}
return "UPDATE `{$table}` a JOIN ( {$update} ) b USING({$where_string}) SET {$set}";
}
/**
* 獲取where
* @param type $where
*/
protected static function where($where) {
$string = '';
foreach ($where as $value) {
$string .= '`' . $value . '`,';
}
return substr($string, 0, strlen($string) - 1);
}
protected static function update($data) {
if (!isset($data[0])) {
return false;
}
$array_keys = array_keys($data[0]);
$count = count($array_keys);
$string = '';
foreach ($data as $key => $value) {
if (count($value) != $count) {
return false;
}
$string2 = ' SELECT ';
foreach ($array_keys as $value2) {
if (!isset($value[$value2])) {
$string2 .= " null " . ' AS `' . $value2 . '`,';
}else{
$string2 .= "'".$value[$value2]."'" . ' AS `' . $value2 .'`,';
}
}
$string2 = substr($string2, 0, strlen($string2) - 1);
$string .= $string2 . ' UNION';
}
return substr($string, 0, strlen($string) - 5);
}
/**
*
* @param type $where
* @param type $data
*/
protected static function set($where, $data) {
if (!isset($data[0])) {
return false;
}
$array_keys = array_keys($data[0]);
foreach ($array_keys as $key => $value) {
if (in_array($value, $where)) {
unset($array_keys[$key]);
};
}
if (empty($array_keys)) {
return FALSE;
}
$string = '';
foreach ($array_keys as $value) {
$string .= 'a.`' . $value . '`=b.`' . $value . '` ,';
}
return substr($string, 0, strlen($string) - 1);
}
}
呼叫方式
// 測試用例 更新會員表的名稱
$sql = UpdateAll::getSql( 'user', ['id'], [
['id' => '1', 'name' => 'test1'],
['id' => '2', 'name' => 'test2'],
['id' => '3', 'name' => 'test3'],
['id' => '4', 'name' => 'test4'],
]);
echo $sql;
本作品採用《CC 協議》,轉載必須註明作者和本文連結