【MySQL】实例收集
OverviewLeetcode -- 627. Swap Salary找出最大最新日期date/datetimeReferenceLeetcode – 627. Swap SalaryGiven a tablesalary, such as the one below, that has mmale and ffemale values. Swap all f and m values (i.e., change all f values to m and vice versa) with asingle update statementand no intermediate temp table.Note that you must write a single update statement,DO NOTwrite any select statement for this problem.Example:| id | name | sex | salary | |----|------|-----|--------| | 1 | A | m | 2500 | | 2 | B | f | 1500 | | 3 | C | m | 5500 | | 4 | D | f | 500 |After running yourupdatestatement, the above salary table should have the following rows:| id | name | sex | salary | |----|------|-----|--------| | 1 | A | f | 2500 | | 2 | B | m | 1500 | | 3 | C | f | 5500 | | 4 | D | m | 500 |Solution:Approach: UsingUPDATEandCASE...WHEN[Accepted]To dynamically set a value to a column, we can useUPDATEstatement together whenCASE...WHEN...flow control statement.UPDATEsalarySETsexCASEsexWHENmTHENfELSEmEND;orUPDATEsalarySETsexIF(sexm,f,m);找出最大最新日期date/datetimeReference:How to get rows with max date when grouping in MySQL?SELECTt.id,m_t.MaxDTT,t.user_idFROM(SELECTMAX(login_datetime_record)ASMaxDTT,user_idFROMtableGROUPBYuser_id)ASm_tINNERJOINtableAStONt.user_idm_t.user_idANDt.login_datetime_recordm_t.MaxDTT;Reference