3

我想结合 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以避免将相同的代码用于不同的用户。

我希望您了解我的问题并知道解决方案。

问候,弗雷德里克

4

1 回答 1

2

如果你反过来做会更容易。
关键是您的客户可以在您执行and之前生成唯一值。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
于 2012-05-05T12:17:57.407 回答