语法:
select 列名1,列名2,列名3... from 表名 [Where 条件1 OR|AND 条件2...];
如果没有条件, 查询整个表的数据!
select * from 表名;
例子:
查询学生名字和数学成绩:
select name, math from student;
DISTINCT关键字:
作用:
去除重复的数据, 重复的数据只保留一条!
例子:
去除所有重复名字并显示
select distinct(name) from student;
别名:
select name 姓名, chinese 语文成绩 from student;
这里的[姓名],[语文成绩]就是自定义的别名.
WHERE 关键字:
作用:
指定查询的特殊条件
例子:
查询数学成绩为88的学生信息
select * from student where math=88;
BETWEEN... AND... 关键字:
作用:
代表限定条件在xxx之间
例子:
查找英语分数在80~90之间的学生信息
select * from student where english between 80 and 90;
注意:
必须是小的数值在and前, 大的在and后.
IN 关键字:
作用:
代表限定条件在xxx里面
例子:
查找语文成绩为80,90,99的学生信息
select * from student where chinese in (80,90,99);
2. 模糊查询
语法:
select 列名1,列名2,列名3... from 表名
[where 列名 like 值];
通配符:
%: 匹配任意多个字符(0 或者1 或者多个).
_: 匹配一个任意字符
例子:
查询名字以小开头的学生信息
select * from student where name like '小%';
查询名字是两个字的学生信息
select * from student where name like '__';
3. 排序查询
语法:
select 列名1, 列名2, 列名3... from 表名
[where 条件1 OR|AND 条件2]
[order by 列名1 ASC|DESC, 列名2 ASC|DESC...];
默认的排序方式是升序(可以省略ASC).
例子:
查询所有学生的信息并以中文成绩降序表示:
select * from student order by chinese desc;
语法:
is null: 为空
is not null: 非空
select * from student where english is not null;
8. NOT关键字
作用:
取反
not in():
不在括号中的那些数据.
select * from student where english not in(80,90,99);
not like:
不包含的那些数据.
select * from student where name not like (%张%);
9. 分组查询
语法:
select 列名1, 列名2, 列名3... from 表名
[where 条件1 OR|AND 条件2]
[group by 分组的列...]
[having 列名1...]
[order by 列名1 ASC|DESC]
[limit 开始查询的位置, 每页的条数];
例子:
查询每个部门的平均薪资
select avg(sal), deptno from emp group by deptno;
查询每种职位的最高薪资和最低薪资
select max(sal), min(sal), job from emp gourp by job;
查询名字中包含o的员工的每种职位平均薪资,且是高于2000的平均薪资,并按照平均薪资降序排列
select job, avg(sal) from emp where ename like '%o%' group by job having avg(sal)>2000 order by avg(sal) desc;
10. 子查询
例子:
查询和SCOTT在同一部门下的所有员工
select * from emp where deptno = (select deptno from emp where ename = 'scott');
将问题拆解! 分解成两部分来看, 再按步骤完成.
语法:
SELECT... FROM 表名1
INNER JOIN 表名2
ON 连接条件
[WHERE 判断条件]
select 列名1, 列名2... from 表1
inner join 表2 on 表1.字段=表2.字段
[where 判断条件]
例子:
查询薪资在2000-3000范围的的所有员工姓名和他所在的部门名字
select e.name,d.name from employee e
inner join department d on e.dept_id = d.id
where salary between 2000 and 3000;
12.2 外连接
语法:
SELECT … FROM join_table1 (LEFT | RIGHT ) JOIN join_table2 ON join_condition WHERE where_definition;
LEFT(左外连接):
左表列出全部,右表只列出匹配的记录
RIGHT(右外连接):
右表列出全部,左表只列出匹配的记录
13. 多表连接
语法:
SELECT * FROM 表名1
INNER JOIN 表名2 ON join_condition1
INNER JOIN 表名3 ON join_condition2;