带有from子句的sql update语句用于验证?

时间:2014-05-12 07:21:23

标签: mysql sql sql-update

我有一个更新操作,我一次对多个用户执行(值保持不变)。出于验证原因,是否可以将表连接到更新语句?

例如,以下是我的发言:

$user_set = array(1, 5, 10, 15, .....)

//update 'changed' status for ALL selected users at once
$stmt = $db->prepare("
    UPDATE users
    SET changed = ?
    WHERE user_id IN(". implode(', ', array_fill(1,count($user_set),'?')) .")   
");

array_unshift($user_set, 1);    
$stmt->execute($user_set);

在一个完美的场景中,我想将一个表(计算机)加入到users表中以验证帐户所有权,以及此更新是否“有效”且是否应该发生。

我之前发现我可以完全使用DELETE,但也可以使用UPDATE完成吗?使用我想要的验证删除示例:

$selected = array(1, 5, 10, 15, .....)

$stmt = $db->prepare("
    DELETE del_table.*
    FROM some_table as del_table
    LEFT JOIN
        users
        on users.user_id = del_table.user_id
    LEFT JOIN
        computers
        on computers.computer_id = users.computer_id            
    WHERE computers.account_id = ? AND del_table.activity_id IN(". implode(', ', array_fill(1,count($selected),'?')) .")    
");

// use selected array and prepend other data into the array so binding and execute work in order
array_unshift($selected, $_SESSION['user']['account_id']);  
$stmt->execute($selected);

编辑(解决方案):

谢谢Alex ......它有效!

$selected = array(5,10,12,13);

$stmt = $db->prepare("
    UPDATE users
    INNER JOIN computers
        on computers.computer_id = users.computer_id    
    SET changed = ?
    WHERE computers.account_id = ? AND users.user_id IN(". implode(', ', array_fill(1,count($selected),'?')) .")    
");

array_unshift($selected, 1, $_SESSION['user']['account_id']);   
$stmt->execute($selected);

2 个答案:

答案 0 :(得分:2)

是的,您可以在多表语法部分下as documented here

UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]

您只需要确保正确订购陈述。

UPDATE my_table
  INNER JOIN other_table
   ON my_table.col2 = othertable.col2
SET my_table.col = 'foo'
WHERE other_table.col = 'bar'

答案 1 :(得分:0)

试试这个

$stmt = $db->prepare("
UPDATE users
SET changed = ?
from users
JOIN computers on computers.computer_id = users.computer_id   
WHERE user_id IN(". implode(', ', array_fill(1,count($user_set),'?')) .")   
");