简体   繁体   中英

MySQL select and update in one statement

I'd would like to have an MySQL command
UPDATE.....SELECT to update my Previous_Change_Date as the below table.

could anyone please help?

+----------------+-------------+----------------------+
| Product_Number | Change_Date | Previous_Change_Date |
+----------------+-------------+----------------------+
|       30000319 |  1178581980 |           1178581860 |
|       30000319 |  1178581860 |           1170916740 |
|       30000319 |  1170916740 |           1138779000 |
|       30000319 |  1138779000 |                 NULL |
|       30000327 |  1178581860 |           1138779000 |
|       30000327 |  1138779000 |                 NULL |
|       30000348 |  1170916740 |           1162451400 |
|       30000348 |  1162451400 |                 NULL |
|       30000443 |  1195713360 |           1191287160 |
|       30000443 |  1191287160 |           1184720940 |
|       30000443 |  1184720940 |           1176421080 |
|       30000443 |  1176421080 |           1173766980 |
|       30000443 |  1173766980 |           1173050460 |
|       30000443 |  1173050460 |           1170816780 |
|       30000443 |  1170816780 |           1170496980 |
|       30000443 |  1170496980 |           1166078340 |
|       30000443 |  1166078340 |                 NULL |
+----------------+-------------+----------------------+

I would suggest to use a mysql stored procedure . This way you could have the luxury of variables and for loops. This would be a lot easier to implement and maintain.

You could use this post as an introductive tutorial.

Hope I helped!

I would recommend using a trigger on insert, here's a fiddle with trigger

trigger fiddle

but if you don't want here's what you can do:

INSERT INTO table_name (Product_Number, Change_Date, Previous_Change_Date) 
VALUES (product_num_value, change_date_value, 
(SELECT date FROM (SELECT MAX(Change_Date) AS date FROM table_name 
WHERE Product_Number='product_num_value') as temp_table));

You have to change table_name to your actual table_name and change the values product_num_value and change_date_value

Here's a fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM