先新建两张表添加些数据
基本查询
SELECT * FROM person -- 数据量大情况不用
SELECT id,name FROM person -- 常用
第二行代表在 person 这张表中查询 id 列、name 列;没有 WHERE 条件代表查询全部
条件查询
SELECT id,NAME,dept FROM person WHERE dept=1
SELECT id,name FROM person WHERE NAME LIKE '%大%'
第一行代表在 person 这张表中查询 id 列、name 列、dept(部门)列,WHERE 条件是 部门序号为 1 则查询显示,应显示研发部;
排序
关键字: ORDER BY
降序关键字:DESC
升序关键字: ASC
SELECT id,NAME,dept,age FROM person ORDER BY age DESC -- 降序排序
SELECT id,NAME, dept,age FROM person ORDER BY age -- 默认就是升序排序
SELECT id,NAME, dept,age FROM person ORDER BY age ASC -- 升序排序
ORDER BY age 代表根据 age(年龄)进行排序
ORDER BY age DESC 代表根据年龄进行降序排序
ORDER BY age ASC 代表根据年龄进行升序排序
分页查询
关键字: LIMIT
SELECT id,name,dept,age FROM person LIMIT 0,5 -- (从第条数据开始-1),每页展示几条数据
SELECT id,name,dept,age FROM person LIMIT 5,5
SELECT id,name,dept,age FROM person LIMIT 10,5
LIMIT 0,5 代表从第一条数据开始,展示5条数据…以此类推
聚合函数
SELECT count(*) AS '总计' FROM person-- 查询一张表有多少条数据,括号内可以是0或者*;
SELECT sum(age) FROM person-- 求和
SELECT avg(age) FROM person-- 求平均值
SELECT max(age) FROM person-- 求最大值
SELECT min(age) FROM person-- 求最小值
SELECT CAST(avg(age) as decimal(10,0)) as avg from person-- 转换类型,四舍五入
分组查询
关键字:GROUP BY
SELECT dept,count(0) AS '部门人数',avg(age) AS '平均年龄' from person GROUP BY dept;
代表从 person 这张表中查询部门,部门人数,部门平均年龄,根据 dept 进行分组
分组后查询
SELECT dept,count(0),avg(age) from person where age>8 GROUP BY dept having avg(age)>50;
代表从 person 这张表中查询部门,部门人数,部门平均年龄,根据 dept 进行分组,查询部门平均年龄超过50岁的部门;
子查询
SELECT id,name,age,dept FROM person WHERE dept IN (SELECT id FROM dept WHERE dept='人事部')
相当于在查询中嵌套了一个查询
以上代表先从 person 这张表中查询id,name,age,dept;WHERE查询条件为 dept 在 dept 这张表中的dept列下的人事部,因为dept这张表中的id为部门序号,person这张表中dept也是部门序号
内连接
关键字: INNER JOIN
SELECT * FROM person INNER JOIN dept ON person.dept=dept.id
SELECT person.id as pid,person.`name` as pname,person.age as page,dept.id as did,dept.dept as ddept FROM person INNER JOIN dept on person.dept=dept.id
第一行代表 查询 person 这张表中的所有数据,以及 dept 中的数据,再将与person中的dept和dept表中的id 对应
第二行同理,只是给person中的字段用 AS 进行了重新命名,as也可以省略,空格就行
隐式内连接
select * from person,dept where person.dept=dept.id
仅将关键字INNER JOIN替换为 WHERE
外连接
左外连接是以左边的表为主表,查询的结果只关注左表,不在乎右边
SELECT person.id as pid,person.`name` as pname,person.age as page,dept.id as did,dept.dept as ddept FROM person LEFT OUTER JOIN dept ON person.dept=dept.id
右外连接是以右边的表为主表,查询的结果只关注右表,不在乎左边
SELECT person.id as pid,person.`name` as pname,person.age as page,dept.id as did,dept.dept as ddept FROM person RIGHT OUTER JOIN dept ON person.dept=dept.id