Вопрос

I have an update operation that I perform on multiple users at once (the value stays the same). Is it possible to join tables to an update statement for reasons of validation?

For instance, here is my statement at the moment :

$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);

In a perfect scenario I would like to join one table (computers) to the users table to validate account ownership and if this update is 'valid' and should occur or not.

I found out earlier I can do EXACTLY that with DELETE, but can it be done with UPDATE as well? Example delete using validation I want :

$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);

EDIT (SOLUTION) :

Thanks Alex... it works!

$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);
Это было полезно?

Решение

Yes, you can, as documented here under the multi-table syntax section.

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

You just need to make sure you order the statements correctly.

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

Другие советы

try this

$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),'?')) .")   
");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top