--创建测试数据库test show databases ; create database if not exists test; use test;
一、关系运算
1、等值比较:=
select 1 where 1 = 1; --1
select 1 where 0 = 1; --NULL
2、不等值比较:<>
select 1 where 1 <> 2; --1
select 1 where 2 <> 2; --NULL
3、小于比较:<
select 1 where 1 < 2; --1
select 1 where 3 < 2; --NULL
4、小于等于比较:<=
select 1 where 1 <= 2; --1
select 1 where 3 <= 2; --NULL
5、大于比较:>
select 1 where 3 > 2; --1
select 1 where 1 > 2; --NULL
6、大于等于比较:>=
select 1 where 3 >= 2; --1
select 1 where 1 >= 2; --NULL
7、空值判断:IS NULL
select 1 where null is null ; --1
select 1 where 1 is null ; --NULL
8、非空判断:IS NOT NULL
select 1 where 1 is not null ; --1
select 1 where null is not null ; --NULL
9、LIKE 比较:LIKE
--字符 ”_” 表示任意单个字符、字符 ”%” 表示任意数量的字符
select 1 where 'footb' like 'foot_'; --1
select 1 where 'football' like 'foot____'; --1
select 1 where 'football' like 'foot%'; --1
select 1 where 'f' like 'foot_'; --NULL
--注意:否定比较时候用 NOT A LIKE B
select 1 where not 'f' like 'foot_'; --1
10、JAVA的LIKE 比较:RLIKE
select 1 where 'football' rlike '^f.*l$'; --1
11、正则匹配:REGEXP
select 1 where 'football' regexp '^f.*l$'; --1
二、数学运算
1、加法操作:+
select 1 + 2; --3
2、减法操作:-
select 1 - 0.5; --0.5
3、乘法操作:*
select 1 * 2; --2
4、除法操作:/
select 1 / 2; --0.5
5、取余操作:%
--通过 round 指定精度
select 5 % 2; --1
select 2.3456 % 2; --0.3456
select round(2.3456 % 2,2); --0.35
6、位与操作:&
select 4 & 8; --0
7、位或操作:|
select 4 | 8; --12
8、位异或操作:^
select 4 ^ 8; --12
9、按位取反操作:~
select ~ 4; -- -5
三、逻辑运算
1、逻辑与操作:AND
select 1 where 1 = 1 and 2 = 2; --1
2、逻辑与操作:OR
select 1 where 1 = 1 or 1 = 2; --1
3、逻辑非操作:NOT
select 1 where not 1 = 2; --1
四、条件运算
1、IF 函数:IF
select if(1=2,100,200); --200
2、非空查找函数:COALESCE
--返回参数中的第一个非空值;如果所有值都为 NULL,那么返回NULL。
select coalesce(null,'100',null,'50'); --100
3、条件判断函数:CASE
--3.1 描述:如果 a 等于 b,那么返回 c;如果 a 等于 d,那么返回 e;否则返回 f。
select case 100 when 50 then 'tom' when 100 then 'jack' else 'ketty' end ; --jack
--3.2 描述:如果 a 为 TRUE,则返回 b;如果 c 为 TRUE,则返回 d;否则返回 e。
select case when 1 = 2 then 'tom' when 1 = 1 then 'jack' else 'ketty' end ; --jack
五、数值计算
1、近似函数:round
--说明:返回 double 类型的整数值部分 (遵循四舍五入)
select round(3.1415926); --3
2、指定精度近似函数:round
--说明:返回指定精度 d 的 double类型
select round(3.1415926,4); --3.1416
3、向下取整函数:floor
select floor(3.1415926); --3
4、向上取整函数:ceil
select ceil(3.1415926); --4
5、向上取整函数:ceiling
select c