I need Primary keys of the affected rows to be returned after updating a table in MYSQL.

帅比萌擦擦* 提交于 2019-12-25 05:12:21

问题


I need Primary keys of the affected rows to be returned after updating a MYSQL table using my PHP Code. Is there anyway to achieve this?


回答1:


You will need to fetch the primary keys before performing the UPDATE:

SELECT primary_key_columns FROM my_table WHERE status = 'O';
UPDATE my_table SET status = 'E' WHERE status = 'O';

However, if you have concurrent connections that might alter my_table between the two statements, it's possible that the results of the keys returned by the first SELECT statement will not fully match the records updated by the second UPDATE statement.

To prevent this, you would need to perform the operations in a transaction (but note that transactions require support from your storage engine - InnoDB is usually used for this purpose):

START TRANSACTION;
SELECT primary_key_columns FROM my_table WHERE status = 'O' FOR UPDATE;
UPDATE my_table SET status = 'E' WHERE status = 'O';
COMMIT;



回答2:


One way of doing what you want is previously SELECT the primary keys with the conditions for the update BEFORE you do the update.

If your query is

Update * from "table" where Y

you would have to do the following:

Select "Primary key" from "table" where Y

Update X from "table" where Y

Hope this helps!



来源:https://stackoverflow.com/questions/10663338/i-need-primary-keys-of-the-affected-rows-to-be-returned-after-updating-a-table-i

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