MySQL - SELECT then UPDATE

这一生的挚爱 提交于 2020-05-10 04:06:45

问题


I have a script written in PHP which has this line which is working correctly for selecting the data i need;

$result = mysql_query("SELECT product_name, sku, qty FROM supplier_dropship_items WHERE supplier_id = '3' AND status = '2'", $db_beb);

What I'm struggling with is a way to update the records I have selected, once selected I need to change the status = '1' so that the next time my script runs it won't pull the same data in the select and will only pull new items in the table which have status 2.

This is my working result thanks to the comments of the accepted answer below;

$result = mysql_query("SELECT id, product_name, sku, qty FROM supplier_dropship_items WHERE supplier_id = '3' AND status = '2' FOR UPDATE", $db_beb); 

while($row = mysql_fetch_assoc($result)) 
{ 
    $sql_table_data[] = $row;
    mysql_query("UPDATE supplier_dropship_items SET status=1 WHERE id='".$row['id']."'", $db_beb); 
} 

回答1:


If supplier_dropship_items has a primary key (it should), then include those fields in the SELECT, then, when you cycle through the results, execute an UPDATE using the primary key to set the status, as in:

UPDATE supplier_dropship_items SET status=1 WHERE <id_field>=<id_value>;

This assumes you are not executing in an concurrent environment. If you are, then you should lock the records for update, by using SELECT... FOR UPDATE. You can read about it here. As far as I know, this works under MySQL on InnoDB tables.




回答2:


Just do the UPDATE when you SELECT it at the same time.

Change this:

SELECT product_name, sku, qty 
FROM supplier_dropship_items 
WHERE supplier_id = '3' AND status = '2';

to this:

UPDATE supplier_dropship_items as t, 
(
    SELECT id, product_name, sku, qty 
    FROM supplier_dropship_items 
    WHERE supplier_id = '3' AND status = '2'
) as temp
SET status = '1' WHERE temp.ID = t.ID;

This is assuming you have an ID column inside your table as this is how it should be set up and how any normalized table would look like.



来源:https://stackoverflow.com/questions/24590256/mysql-select-then-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!