SELECT then immediately DELETE mysql record

后端 未结 5 2035
情深已故
情深已故 2021-01-17 14:14

I have a PHP script that runs a SELECT query then immediately deletes the record. There are multiple machines that are pinging the same php file and fetching data from the s

相关标签:
5条回答
  • 2021-01-17 14:36

    If you're using MariaDB 10:

    DELETE FROM `queue` LIMIT 1 RETURNING *
    

    Documentation.

    0 讨论(0)
  • 2021-01-17 14:36

    well I would use table locks read more here

    Locking is safe and applies to one client session. A table lock protects only against inappropriate reads or writes by other sessions.

    0 讨论(0)
  • 2021-01-17 14:51

    Put your delete queries inside the while loop, just incase you ever want to increase the limit from your select.

    <?php
    $query = mysql_query("SELECT * FROM `queue` LIMIT 1") or die(mysql_error());
    
    while($row = mysql_fetch_array($query)){
        mysql_query("DELETE FROM `queue` WHERE `email` = '" . $row['email'] . "' LIMIT 1") or die(mysql_error());
    }
    ?>
    

    The above code would be just the same as running:

    mysql_query("DELETE FROM `queue` LIMIT 1") or die(mysql_error());
    

    Be careful using your delete query, if the email field is blank, it will delete all rows that have a blank email. Add LIMIT 1 to your delete query to avoid multiple rows being deleted.

    To add a random delay, you could add a sleep to the top of the script,

    eg:

    <?php
    $seconds = mt_rand(1,10);
    sleep($seconds);
    ?>
    
    0 讨论(0)
  • 2021-01-17 14:52

    run an update query that will change the key before you do your select. Do the select by this new key, whicj is known only in the same session.
    If the table is innoDB the record is locked, and when it will be released, the other selects won't find the record.

    0 讨论(0)
  • 2021-01-17 14:59

    You should use subquery as follows...

    <?php
    
    $queryx = "DELETE FROM `queue` WHERE `email` IN (SELECT email FROM `queue` LIMIT 1)";
    $resultx = mysql_query($queryx) or die(mysql_error());
    
    ?>
    

    *Note: Always select only the fields you want... try to avoid select *... this will slow down the performance

    0 讨论(0)
提交回复
热议问题