将SELECT和UPDATE结合使用,避免重复查询

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,以避免相同的代码被不同的用户使用。
我希望您能理解我的问题并知道解决方案。
问候, Frederick
1个回答

2

如果你采用另一种方式,这将更容易。
关键是在执行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

非常感谢这个好主意,我会按照这种方式实现它。 - Frederick Behrends

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接