【问题标题】:Update Table Column in Multiple Rows based on a Selection in SQL根据 SQL 中的选择更新多行中的表列
【发布时间】:2014-07-08 09:43:19
【问题描述】:

我在SQL 中使用Select 语句选择了一组rows,我正在尝试弄清楚如何将此table 中的列更新为基于所述selection 的值。

选择:

SELECT user.userID FROM user WHERE user.status = '1' or user.status = '2' LIMIT 1000 OFFSET 50;

更新:

UPDATE user SET user.status = '3';

我正在寻找的最终结果是将所有selected users 中的status column 更新为“3”。我希望能够在一个SQL query 中做到这一点,而不必循环或任何东西。

感谢您的任何见解!

更新:

对不起!我忘了添加offset。我想选择前 50 个返回行之后的行。 所以我希望前 50 行之后符合条件的所有行,将状态列更改为 3。

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:

    UPDATE user SET user.status = '3' WHERE user.status = '1' or user.status = '2';

    请试试这个查询...

    编辑问题后(根据偏移量)

    尝试以下查询以获取您的偏移量。

    UPDATE user SET user.status = '3' where  user.userID NOT IN(Select
    userid from 
    (SELECT userID as userid FROM user WHERE status = '1' or status = '2' LIMIT 50) 
    as temptbl);
    

    【讨论】:

    【解决方案2】:
    UPDATE user SET user.status = '3' where user.status in ('1', '2');
    

    更新:

    UPDATE user SET user.status = '3' where user.userID in (SELECT user.userID FROM user WHERE user.status = '1' or user.status = '2' LIMIT 1000 OFFSET 50);
    

    【讨论】:

      【解决方案3】:

      请试试这个

      UPDATE user SET user.status = '3' WHERE user.status IN ( '1' , '2' )
      

      【讨论】:

        【解决方案4】:

        新:

        使用两个子选择(感谢 Yograj Sudewad 指出我的错误)

        UPDATE user 
        SET user.status = '3'
        WHERE user.userID IN (
            SELECT userId 
            FROM (
                SELECT user.userID 
                FROM user 
                WHERE user.status = '1' or user.status = '2' 
                LIMIT 1000 OFFSET 50
            ) AS tableWithNoName
        )
        

        旧:

        您也可以在UPDATE 中使用SELECT 中的WHERE 部分。 像这样

        UPDATE user 
        SET user.status = '3'
        WHERE user.status = '1' 
            OR user.status = '2';
        

        但如果你想从 uid 列表中获取 UPDATE,那么:

        <?php
        // The uid list from the select may be 
        $uid_list = array(1,4,7,12,401);
        // then you could make
        $sql = "
        UPDATE user 
        SET user.status = '3'
        WHERE user.userID IN (" . implode(',', $uid_list) , ")
        
        ";
        

        【讨论】:

        • @Guy 然后使用像here 这样的子选择查看我的更新答案
        • 这似乎不起作用。我完全喂它,但它抱怨查询并且失败了。
        • 它到底在抱怨什么?
        • @HerrSerker Mysql 不能允许你直接在内部查询中使用同一张表,因为你正在执行更新数据。
        • MySql 给出的错误如下:“您无法在 FROM 子句中指定目标表 'User' 进行更新”
        猜你喜欢
        • 1970-01-01
        • 2021-09-24
        • 2020-04-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 1970-01-01
        • 2021-03-22
        • 2022-01-06
        相关资源
        最近更新 更多