准备环境

开源数据库MySQL(6)数据库查询语言DQL_mysql

mysql> create database company;
mysql> CREATE TABLE company.employee5(
id int primary key AUTO_INCREMENT not null,
name varchar(30) not null,
sex enum('male','female') default 'male' not null,
hire_date date not null,
post varchar(50) not null,
job_description varchar(100),
salary double(15,2) not null,
office int,
dep_id int
);

开源数据库MySQL(6)数据库查询语言DQL_Linux_02

查看表结构

mysql> insert into company.employee5(name,sex,hire_date,post,job_description,salary,office,dep_id) values 
('jack','male','20180202','instructor','teach',5000,501,100),
('tom','male','20180203','instructor','teach',5500,501,100),
('robin','male','20180202','instructor','teach',8000,501,100),
('alice','female','20180202','instructor','teach',7200,501,100),
('aofa','male','20180202','hr','hrcc',600,502,101),
('harry','male','20180202','hr',NULL,6000,502,101),
('emma','female','20180206','sale','salecc',20000,503,102),
('christine','female','20180205','sale','salecc',2200,503,102),
('zhuzhu','male','20180205','sale',NULL,2200,503,102),
('gougou','male','20180205','sale','',2200,503,102);

开源数据库MySQL(6)数据库查询语言DQL_DQL_03


一、简单查询

查看所有列

SELECT * FROM   表名;

查部分列

SELECT 列1,列2,列3 FROM 表名;

通过四则运算查询年薪

SELECT name, salary, salary*14 FROM employee5;


二、条件查询

单条件查询where

SELECT name,post FROM employee5 WHERE post='hr';
//查询hr部门的员工姓名

多条件查询AND/OR

SELECT name, salary FROM employee5 WHERE salary=6000 OR salary=8000
//查询所有部门的员工,并且工资是6000或者8000的员工

关键字BETWEEN AND 在什么之间

SELECT name,salary FROM employee5 WHERE salary BETWEEN 5000 AND 15000;
//薪资在5000到15000
SELECT name,salary FROM employee5 WHERE salary NOT BETWEEN 5000 AND 15000;
//不在5000~15000

关键字IN集合查询

SELECT name, salary FROM employee5 WHERE salary IN (4000,5000,6000,9000);
//工资是4000,5000,还有9000
SELECT name, salary FROM employee WHERE salary NOT IN (4000,5000,6000,9000);
//工资不是4000,不是5000,不是9000

关键字IS NULL

SELECT name,job_description FROM employee5 WHERE job_description IS NULL;
//没有岗位描述的
SELECT name,job_description FROM employee5 WHERE job_description IS NOT NULL;
//有岗位描述的

关键字LIKE模糊查询

SELECT * FROM employee5 WHERE name LIKE 'al%';
//员工名为"al"开头

三、查询排序

SELECT * FROM 表名 ORDER BY 工资的列名 ASC;
//以工资升序排列
SELECT * FROM 表名 ORDER BY 工资的列名 DESC;
//以工资降序排列
SELECT * FROM employee5 ORDER BY salary DESC LIMIT 5;
工资最高的前五名