Mysql基础之查询的基本语句
1.查询的基本语法:
1.select * from 表名
from关键字后面写表名,表示数据来源于是这张表。
select后面写表中的列名,如果是*表示在结果中显示表中所有的列。
在select后面的列名部分,可以使用as为列起别名,这个别名出现在结果集中。
如果要查询多个列,之间使用逗号分隔
2.消除重复行:
在select后面列的前使用distinct可以消除重复的行。
select distinct gender from students;
3.条件
使用where子句对表中的数据筛选,结果为true的行会出现在结果集中
select * from 表名 where 条件
where是对行进行筛选的。
4.比较运算符:
等于 =
大于 >
大于等于 >=
小于 <
小于等于 <=
不等于 !=或者< >
查询编号大于3的学生
select * from students where id > 3
5.查询编号不大于4的科目
select * from subjects where id<3
6.查询姓名不是‘yue’的学生
select * from students where name!=‘yue ’;
7.查询没有删除的学生
select * from students where isdelete=0;
8.逻辑运算符:
and
or
not
查询编号大于三的男生
select * from students where id>3 gender=1;
9.查询编号小于3或者没有被删除的学生
select * from students where id<4 or isdelete=0;
10.知识补充:
在MySQL中关键字和字段不区分大小写
语言分为类C类B;
类C区分大小写
类B不区分大小写
11.模糊查询
like
%表示一个任意字符
_表示一个任意字符
查询姓含有y的学生
select * from students where name like 'y%';
12.查询含yu并且是三个字母的学生
select * from students wehere name like ‘yu_’;
13.查询中间的字符:
select * from students where name like ‘%u%’;
14.查询姓含有y的或者含有tian 的学生
select * from students where name like ‘y%’ or name like '%tian';
15.范围查询:
in表示在一个非连续的范围内
查询编号是1或3的学生
select * from students where id in(1,3);
16.between.....and...表示在一个连续的范围内
查询学生是2到4的学生
select * from students where id between id 3 and 8;
17.查询3到8的男生:
18.空判断:
注意:null与 ' '是不同的
判空 is null
19.查询生日不为空的:
20.查询没有填写的地址的学生
select * from students where hometown is null;
判非空 is not null
查询填写了地址的学生
select * from students where hometown is not null
查询填写了生日的女生:
select * from students where birthday is not null and gender=0;
20.优先级:
小括号,not,比较运算符,逻辑运算符
and比or先运算,如果同时出现并希望先算or,需要结合()使用。