数据库_02_条件查询

#进阶2:条件查询

语法:

    select 
          查询列表
    from
         表名
    where
         筛选条件

分类:
1.按条件表达式筛选
条件运算符:>, < ,=, !=, <> ,>=, <=
2.按逻辑表达式筛选
逻辑运算符:&&, || ,! , and, or, not
3. 模糊查询
like,between and,in,is null
#----------------------------------------------------
#1.按条件表达式筛选
#案例1:查询工资>12000的员工信息

SELECT * FROM employees WHERE salary>12000;

#案例2:查询部门编号不等于90号的员工名和部门编号

SELECT last_name,employee_id FROM employees WHERE department_id<>90;

#2.按逻辑表达式筛选
#案例1:查询工资在10000到20000之间的员工名。工资以及奖金

SELECT last_name,salary,commission_pct FROM employees WHERE salary>=10000 AND salary<=20000;

#案例2:查询部门编号不是在90到110之间,或者工资高于15000的员工信息

SELECT * FROM employees WHERE department_id<90 OR department_id>110 OR salary>15000;

#3.模糊查询
/*1.like
特点:
一般和通配符搭配使用
通配符:
% 任意多个字符,包含0个字符
_ 任意单个字符
*/
#案例1:查询员工名中包含字符a的员工信息

SELECT * FROM employees WHERE last_name LIKE '%a%';

#案例2:查询员工名中第三个字符为e,第五个字符为a的员工名和工资

SELECT last_name,salary FROM employees WHERE last_name LIKE '__n_l%';

#案例3:查询员工名中第二个字符为_的员工名

SELECT last_name FROM employees WHERE last_name LIKE '_\_%';
SELECT last_name FROM employees WHERE last_name LIKE '_S_%' ESCAPE 'S';

/*2.between and
1.使用其能提高简洁度
2.包含临界值
3.两个临界值不要调换顺序
*/
#案例1:查询员工编号在100到120之间的员工信息

SELECT * FROM employees WHERE employee_id BETWEEN 100 AND 120;

/*3.in
含义:判断某字段的值是否属于in列表中的某一项
特点:
1.提高简洁度
2.列表值类型必须统一或兼容
*/
#案例:查询员工的工种编号是IT_PROT,AD_VP,AD_PRES 中的一个员工名和工种编号

SELECT last_name,job_id FROM employees WHERE job_id='IT_PROT' OR job_id='AD_VP'; 
SELECT last_name,job_id FROM employees WHERE job_id IN('IT_PROT','AD_VP','AD_PRES');

/*4.is null
=或<>不能用于判断null值
而null或is not null可以判断null值
*/
#案例1:查询没有奖金的员工名和奖金率

SELECT last_name,commission_pct FROM employees WHERE commission_pct IS NULL;

#安全等于 <=>
#案例1:查询没有奖金的员工名和奖金率

SELECT last_name,commission_pct FROM employees WHERE commission_pct <=>NULL;

#案例2:查询工资为12000的员工信息

SELECT last_name,salary FROM employees WHERE salary <=> 12000;

#is null pk <=>
/*
is null:仅仅可以判断NULL值,可读性较高,建议使用
<=>:既可以判断NULL值,又可以判断普通的数值,可读性较低
*/

#测试
#1.查询员工号为176员工姓名和工资

SELECT 
     last_name,department_id,salary*12*(1+IFNULL(commission_pct,0))
AS 
     年薪 
FROM 
     employees WHERE employee_id=176;

#2.其他

SELECT last_name,department_id FROM employees WHERE department_id IN(20,50);
SELECT last_name,salary FROM employees WHERE commission_pct IS NOT NULL;
SELECT last_name FROM employees WHERE last_name LIKE '__a%';
SELECT last_name FROM employees WHERE last_name LIKE '%a%e%' OR '%e%a%';
SELECT last_name,salary FROM employees WHERE commission_pct IS NULL AND salary<18000;
SELECT * FROM employees WHERE job_id NOT LIKE'IT%' OR salary=12000;
DESC departments;
SELECT DISTINCT location_id FROM departments;
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页