select
字段
from
表名
where
条件
group by
分组字段
having
分组之后的操作
order by
排序
limit
分页限定
-- 方便起见先创建一张表
CREATE TABLE student (
id int, -- 编号
name varchar(20), -- 姓名
age int, -- 年龄
sex varchar(5), -- 性别
address varchar(100), -- 地址
math int, -- 数学
english int -- 英语
);
INSERT INTO student(id,NAME,age,sex,address,math,english) VALUES (1,'马云',55,'男',
'杭州',66,78),(2,'马化腾',45,'女','深圳',98,87),(3,'马景涛',55,'男','香港',56,77),(4,'柳岩'
,20,'女','湖南',76,65),(5,'柳青',20,'男','湖南',86,NULL),(6,
'刘德华',57,'男','香港'
,99,99),(7,'马德',22,'女','香港',99,99),(8,'德玛西亚',18,'男','南京',56,65);
-- 基础查询
-- 1.显示表中所有列的信息
select * from 表名;
select * from student;
--2查询表中特定列的数据
select 字段1,字段2,... from 表名;
select id,name,age from student;
-- 3.去除重复元素,使用distinct关键字
select distinct 字段 from 表名;
select distinct address from student;
--4.计算列 用于数值类型的列进行四则运算
select (字段1+字段2) from 表名;
select name,(math+english) from student;
--5.起别名,用关键字as(as可以省略,字段名与别名用空格隔开即可)
SELECT 字段名 1 AS 别名1, 字段名 2 AS 别名2... FROM 表名;
select name as 姓名,math as 数学,english as 英语 from student;
--条件查询
1.使用where关键字
2.运算符:(具体含义不解释了,会举例)
>
<
>=
<=
=
<> != --不等于
between ... and...
in(集合)
like '%字符%' 模糊查询 知到 % 和 _ 使用
IS NULL
3.比较运算符
and 或 &&
or 或 ||
not 或 !
select * from student where math > 70;
select * from student where english <= 80;
select * from student where sex = '女';
select * from student where sex <> '女';
select * from student where math > 70 and math < 80;
select * from student where math between 70 and 80;
select * from student where age in(55,44,33,20);
SELECT * FROM student WHERE NAME LIKE '柳_';--查询名字为2个字且第一个字为柳
SELECT *FROM student WHERE NAME LIKE'马%';-- %代表0个或多个字符,进行模糊查找
select * from student where english is not null;
select * from student where english is null;
-- 排序查询
order by 字段1 排序方式1,字段2 排序方式2 ...
排序方式:
升序 ASC
降序 DESC
SELECT * FROM student ORDER BY age DESC;
select * from student order by math desc,english desc;
-- 聚合函数
将一列数据作为一个整体,进行纵向计算
count max min sum avg 不会计算null值
SELECT COUNT(NAME) FROM student;
select count(english) from student;
SELECT COUNT(IFNULL(english,0)) FROM student;
select count(id),max(math),min(english),sum(math),avg(english) from student;
-- 分组查询
分组后查询字段只用分组字段和聚合函数
SELECT sex,AVG(math) FROM student GROUP BY sex;
SELECT sex,AVG(math),COUNT(id) FROM student GROUP BY sex;
SELECT sex,AVG(math),COUNT(id) FROM student WHERE math > 70 GROUP BY sex;
SELECT sex,AVG(math),COUNT(id) FROM student WHERE math > 70 GROUP BY sex HAVING COUNT(id)>2;
-- where和having区别
1. where 在分组之前进行限定,如果不满足条件,则不参与分组。having在分组之后进行限定,如果不满足结果,则不会被查询出来
2. where 后不可以跟聚合函数,having可以进行聚合函数的判断。