Mysql基础之查询的基本语句

 

1.查询的基本语法:


1.select * from 表名

from关键字后面写表名,表示数据来源于是这张表。
select后面写表中的列名,如果是*表示在结果中显示表中所有的列。
在select后面的列名部分,可以使用as为列起别名,这个别名出现在结果集中。
如果要查询多个列,之间使用逗号分隔

Mysql基础之查询的基本语句

2.消除重复行:

在select后面列的前使用distinct可以消除重复的行。
select distinct gender from students;

Mysql基础之查询的基本语句

Mysql基础之查询的基本语句

3.条件

使用where子句对表中的数据筛选,结果为true的行会出现在结果集中
select * from 表名 where 条件

Mysql基础之查询的基本语句

where是对行进行筛选的。

4.比较运算符:

等于   =
大于   >
大于等于  >=
小于  <
小于等于  <=
不等于  !=或者< >
查询编号大于3的学生
select * from students where id >  3

Mysql基础之查询的基本语句

5.查询编号不大于4的科目

select * from subjects where id<3

Mysql基础之查询的基本语句

6.查询姓名不是‘yue’的学生

select * from students where name!=‘yue ’;

Mysql基础之查询的基本语句

7.查询没有删除的学生

select * from students where isdelete=0;

Mysql基础之查询的基本语句

8.逻辑运算符:

and 
or
not
查询编号大于三的男生
select * from students where id>3 gender=1;

Mysql基础之查询的基本语句


9.查询编号小于3或者没有被删除的学生

select * from students where id<4 or isdelete=0;

Mysql基础之查询的基本语句

10.知识补充:

在MySQL中关键字和字段不区分大小写

语言分为类C类B;
类C区分大小写
类B不区分大小写

11.模糊查询

like
%表示一个任意字符
_表示一个任意字符
查询姓含有y的学生
select * from students where name like 'y%';

Mysql基础之查询的基本语句

12.查询含yu并且是三个字母的学生

select * from students wehere name like ‘yu_’;

Mysql基础之查询的基本语句

13.查询中间的字符:

select * from students where name like ‘%u%’;

Mysql基础之查询的基本语句

Mysql基础之查询的基本语句

14.查询姓含有y的或者含有tian 的学生

select * from students where name like ‘y%’ or name like '%tian';

Mysql基础之查询的基本语句

15.范围查询:

in表示在一个非连续的范围内
查询编号是1或3的学生
select * from students where id in(1,3);

Mysql基础之查询的基本语句

16.between.....and...表示在一个连续的范围内

查询学生是2到4的学生
select * from students where id between id 3 and 8;

Mysql基础之查询的基本语句


17.查询3到8的男生:

 

Mysql基础之查询的基本语句

18.空判断:

注意:null与 ' '是不同的
判空 is null

Mysql基础之查询的基本语句

19.查询生日不为空的:

Mysql基础之查询的基本语句


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;

Mysql基础之查询的基本语句

20.优先级:

小括号,not,比较运算符,逻辑运算符
and比or先运算,如果同时出现并希望先算or,需要结合()使用。