SQL / PHP条件SELECT和UPDATE

时间:2014-08-18 11:43:35

标签: php mysql sql

我正在尝试从下表中的codes列返回5个未使用的值,然后将相关行中的used设置为1.

|--- codes ---| | used |
| FIomQVu71l  | |   0  |
| 4TW0lwLWNK  | |   0  |
| SjzLB2Shzr  | |   0  |
| uTWJrtCgh4  | |   0  |
| tLwOwYGz5R  | |   0  |
| byEhzYMWJG  | |   0  |
| XFBmGzDGIR  | |   0  |

我设法让代码工作从codes输出5个随机值,其中使用了= 0

<?php
$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
while($rows = mysql_fetch_array($records)){
echo "Code: " . $rows['codes'] . "<br />";
?>

但是现在我很遗憾如何更新每个输出used的{​​{1}}值。我的所有尝试都将codes的每个实例更新为1,而不仅仅是与5 used相关联的实例

2 个答案:

答案 0 :(得分:0)

您可以将行存储在临时表中。请注意,这并不完全是并发安全的。如果insertupdate之间存在其他查询,则可能会获取相同的行。

CREATE TEMPORARY TABLE IF NOT EXISTS tmp_codes (codes varchar(50));

-- Get five new rows
INSERT INTO tmp_codes
        (codes)
SELECT  codes
FROM    code_table
WHERE   used = 0
ORDER BY
        rand()
LIMIT   5;

-- Update the five rows
UPDATE  code_table
SET     used = 1
WHERE   codes in
        (
        SELECT  codes
        FROM    tmp_codes
        );

-- Return to application
SELECT  codes
FROM    tmp_codes;

DROP TABLE tmp_codes;

Example at SQL Fiddle.

答案 1 :(得分:0)

您应该执行更新查询:

$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
$codes = array();
while($rows = mysql_fetch_array($records)){
    echo "Code: " . $rows['codes'] . "<br />";
    $codes[] = "'" . $rows['codes'] . "'";
}
$updateSql = "UPDATE code_table SET used = 1 WHERE codes in(" . implode (',' , $codes ) . ")";
$res = mysql_query($updateSql, $connection);