mysql用一条update语句更新多条记录

gcuhipw9  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(376)

我有一个动态生成的update语句,它如下所示:

UPDATE `maildespatch` SET `RL_TktNumber`= Null ,`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks' WHERE `Table_ID` = 1 , 
UPDATE `maildespatch` SET `RL_TktNumber`= Null ,`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks' WHERE `Table_ID` = 2 , 
UPDATE `maildespatch` SET `RL_TktNumber`= Null ,`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks' WHERE `Table_ID` = 5 , 
UPDATE `maildespatch` SET `RL_TktNumber`= Null,`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks' WHERE `Table_ID` = '68'

数据来自用户对html表字段的输入,根据这些字段,通过ajax()调用动态生成这些语句。有没有办法保存所有这些数据,以便在mysql中更通用地保存/更新?我不想创建一个临时mysql表来保存数据,然后从主表更新。

ldioqlga

ldioqlga1#

您可以按如下方式运行这4个查询:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

    $sql = "UPDATE `maildespatch` SET `RL_TktNumber`= '11',`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks'  WHERE `Table_ID` = '1'; 
            UPDATE `maildespatch` SET `RL_TktNumber`= 'Null',`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks'  WHERE `Table_ID` = '2'; 
            UPDATE `maildespatch` SET `RL_TktNumber`= '33',`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks'  WHERE `Table_ID` = '5';
            UPDATE `maildespatch` SET `RL_TktNumber`= 'Null',`SxRemote_IP`= '::1' ,`SxRemotename`= 'Raks'  WHERE `Table_ID` = '68'";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

或者,如果以数组形式传递数据,则可以执行循环:

foreach ($alldata as $data)
{
    //your queries will go here
}
n3ipq98p

n3ipq98p2#

一种更通用的方法是在mysql中调用存储过程(即用户定义的函数-udf)并传递必要的参数。
存储过程是数据库中可重用的一段代码(如后端代码中的函数),可以封装一段逻辑。这里看一下存储过程的mysql文档。
使用它们,您可以任意通用—例如,为最常传递的值设置默认值(如 SxRemote_IP = '::1' ,SxRemotename = 'Raks' )因此,您不必通过网络发送它们并在前端代码中省略它们。

rqcrx0a6

rqcrx0a63#

你需要一个 CASE 表达式:

UPDATE maildespatch
SET RL_TktNumber = CASE WHEN Table_ID = '1' THEN '11'
                        WHEN Table_ID = '2' THEN NULL
                        WHEN Table_ID = '5' THEN '33'
                        WHEN Table_ID = '68' THEN NULL END,
    SxRemote_IP = '::1',
    SxRemotename = 'Raks'
WHERE
    Table_ID = IN('1', '2', '5', '68');

注意,如果 Table_ID 如果是整数列,则应该正确地与整数进行比较,例如 WHERE 子句应如下所示:

WHERE Table_ID = IN(1, 2, 5, 68)

相关问题