文章目录
查看表中的所有数据
select * from tb_users;
用于指代表中的所有列
查看表中的指定列
select username,password,birth from tb_users;
针对查看的列重新起名[别名]
select username as unmame, password pwd from tb_users; # 这里可以使用as,也可以省略
除了特定列中的数据外,在查询过程中允许进行计算
now()获取数据库服务器的系统当前时,年月日时分秒
year(date) 获取指定日期的年份
select username,year(now())-year(birth) from tb_users;
select username,year(now())-year(birth) age from tb_users;
带条件查询 select * from 表名称 where 条件
= 是比较运算符,不是赋值 !=不等于 >大于 < 小于 >= <=
查询所有未删除的数据【逻辑删除 deleted boolean default 0】
select * from tb_users where deleted=0;
select * from tb_users where deleted=1;
查询18岁以上的人
select * from tb_users where year(now())-year(birth)>18
逻辑运算 and与 or或 not非
查询18岁的男生
select * from tb_useres where year(now())-year(birth)=18 and sex=1
查询1989出生的用户或者所有女性用户
select * from tb_users where year(birth)=1989 or sex=0;
查询不是1989年出生的用户
select * from tb_users where year(birth)!=1989
select * from tb_users where not(year(birth)=1989)
针对null不能使用=或者!=进行判断
查看口令为空的用户
select * from tb_users where password is null; -- 这里不能使用=null,否则返回为null
select * from tb_users where password is not null;
主要针对数值类型
查询1989年到2000年出生的用户
between 小值 and 大值 要求数据在指定的范围内,包括两端
not between..and
select * from tb_users where year(birth)>=1989 and year(birth)<=2000
select * from t3 where id between 'ac' and 'ca'; 也可以用于字符串类型,含义比较奇怪
主要针对字符串类型
查询所有姓zhang的用户
like 需要配合_或者%进行模糊查询 not like
_用于指代一个任意字符,%用于指代任意多个任意字符
select * from tb_users where username like 'zhang%'
查询名称中有国字的
select * from tb_users where username like '%国%';
查询张xx用户
select * from tb_users where usenrame like '张__'
组合 %张_ _张%
select * from tb_users where birth like '1989%'; 在MySQL8中语法正确,birth是date类型
针对离散值的等值判断
in或者not in
查看1989、2004、1878、2020年出生的用户
select * from tb_users where year(birth) in (1989,2004,1878,2020);
select * from tb_users where year(birth)=1989 or year(birth)=2004 or year(birth)=1878 or year(birth)=2020;