【问题标题】:Combine SELECT and UPDATE to avoid duplicate selects结合 SELECT 和 UPDATE 以避免重复选择
【发布时间】:2012-05-14 17:55:29
【问题描述】:

我想组合一个 SELECT 和 UPDATE 查询,以避免重复选择行。

这是我的示例代码:

private function getNewRCode() {

    $getrcodesql = "SELECT * FROM `{$this->mysqlprefix}codes` WHERE `used` = 0 LIMIT 1;";
    $getrcodequery = $this->mysqlconn->query($getrcodesql);

    if(@$getrcodequery->num_rows > 0){

        $rcode = $getrcodequery->fetch_array();

        $updatercodesql = "UPDATE `{$this->mysqlprefix}codes` SET `used` =  '1' WHERE `id` = {$rcode['id']};";
        $this->mysqlconn->query($updatercodesql);

        $updateusersql = "UPDATE `{$this->mysqlprefix}users` SET `used_codes` =  `used_codes`+1, `last_code` =  '{$rcode['code']}', `last_code_date` =  NOW() WHERE `uid` = {$this->uid};";
        $this->mysqlconn->query($updateusersql);

        $output = array('code' => $rcode['code'],
                        'time' => time() + 60*60*$this->houroffset,
                        'now' => time()
                        );

        return $output;

    }

}

我想同时执行$getrcodesql$updatercodesql,以避免相同的代码用于不同的用户。

我希望你能理解我的问题并知道解决方案。

您好, 弗雷德里克

【问题讨论】:

    标签: php mysql sql mysqli


    【解决方案1】:

    如果你反过来做会更容易。
    关键是您的客户可以您执行UPDATESELECT 之前生成唯一值。

    used 列的类型更改为其他类型,以便您可以在其中存储 GUID 或时间戳,而不仅仅是 0 和 1。
    (我不是 PHP/ MySQL 专家,所以你可能比我更清楚该使用什么)

    然后你可以这样做(在伪代码中):

    // create unique GUID (I don't know how to do this in PHP, but you probably do)
    $guid = Create_Guid_In_PHP();
    
    // update one row and set the GUID that you just created
    update codes
    set used = '$guid'
    where id in
    (
        select id 
        from codes
        where used = ''
        limit 1
    );
    
    // now you can be sure that no one else selected the row with "your" GUID
    select *
    from codes
    where used = '$guid'
    
    // do your stuff with the selected row
    

    【讨论】:

    • 非常感谢这个好主意,我会这样实现的。
    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多