This question uses MySQL 8.0 and has not been tested in MySQL 5.6, so it is not guaranteed to be correct.
topic
Topic source: Gender change
sex
f
and m
of all data 061f4d0e5de005, use only a single update
statement, and do not generate an intermediate temporary table
create table salary (
id int primary key,
name varchar(255),
sex varchar(255),
salary int
)
insert into salary values
(1, 'A', 'm', 2500),
(2, 'B', 'f', 1500),
(3, 'C', 'm', 5500),
(4, 'D', 'f', 500);
SQL: Method 1
update salary set sex = case sex when 'm' then 'f' else 'm' end;
Parse
If sex = 'm'
, then set to f
, otherwise set to m
.
case sex when 'm' then 'f' else 'm' end
can be achieved using 061f4d0e5de0a1
SQL: Method 2
update salary set sex = if(sex = 'm', 'f', 'm');
Parse
The same idea and method
This is using if(sex = 'm', 'f', 'm')
SQL: Method 3
update salary set sex = char(ascii(sex) ^ ascii('m') ^ ascii('f'));
Parse
Each letter corresponds to a ascii
, use ascii()
to convert the letter to ascii
.
In using XOR, the same number is 0
, 0
and any number XOR is that number.
Then use char
convert the ascii
code into letters
Specific steps:
ascii('m')
is109
andascii('f')
is102
ascii('m') ^ ascii('m') ^ ascii('f')
, it is converted into109 ^ 109 ^ 102
,109
and109
exclusive OR is0
,0
and102
exclusive OR is102
, withchar(102)
the outcome ofm
.ascii('f') ^ ascii('m') ^ ascii('f')
, it is converted into102 ^ 109 ^ 102
, can be exchanged at109
and102
position, so102
and102
exclusive OR is0
,0
and109
exclusive OR is109
, withchar(109)
the outcome off
.
More reference for solving problems: https://github.com/astak16/blog-mysql
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。