mysql makes specific updates based on conditions

Sometimes, ordinary update operations can no longer meet our needs, and we need to make specific updates according to different conditions. For example, a field is directly updated normally, and other fields need to be updated according to conditions. Please see an example below.

Original table data:



demand:

1. For all records, the IS_ENABLE field is changed to 1.

2. For the record with the largest id, the IS_ENABLE time is changed to "2017-09-09 09:09:09", and for the rest of the records, the time is changed to "2017-01-01 00:00:00"


The SQL statement is as follows:

update t_iov_user_car_info set IS_ENABLE=1,
LAST_UPDATED_DATE=
( 
 case when id=(select a.id from (select max(id) id from t_iov_user_car_info uc where uc.USER_ID_CARD=4) a) 
 then '2017-09-09 09:09:09' 
 else '2017-01-01 00:00:00' end
)
 where USER_ID_CARD=4

Results of the:

As you can see, the IS_ENABLE field data has all been changed to 1. Here is a normal change operation.

For other records, the time was changed to: 2017-01-01 00:00:00, and for the record with the largest id (id=233), the time was changed to: 2017-09-09 09:09:09.

This is to do a specific update.


SQL analysis:

Among them, the statement:

select max(id) id from t_iov_user_car_info uc where uc.USER_ID_CARD=4 
It is to query the largest id. So why add in front of this statement

select a.id from? It is because mysql cannot select some values ​​in the same table first, and then update this table (in the same statement), otherwise it will report an error:

"You can't specify target table for update in FROM clause”。

The solution is to select the result of the selection through the intermediate table again, so as to avoid the error.

Note that this problem only occurs in mysql, mssql and oracle will not have this problem.


The following SQL statement:

LAST_UPDATED_DATE=
( 
 case when id=(select a.id from (select max(id) id from t_iov_user_car_info uc where uc.USER_ID_CARD=4) a) 
 then '2017-09-09 09:09:09' 
 else '2017-01-01 00:00:00' end
)

Its meaning is very clear, equivalent to java code:

if(id=最大){
LAST_UPDATED_DATE='2017-09-09 09:09:09' ;
}else{
LAST_UPDATED_DATE='2017-01-01 00:00:00' ;
}

OK, That's all。


Guess you like

Origin blog.csdn.net/u012660464/article/details/78615916