【超详细】MySQL学习笔记汇总(二)之条件查询

MySQL学习笔记汇总(二)

三、进阶2:条件查询

语法:

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

执行顺序:from 表名-》where 条件-》select

分类:
1、按条件表达式筛选

条件运算符:> 、 < 、 = 、 <>(不等于)、 >= 、 <=

2、按逻辑运算符

作用:用于连接条件表达式

逻辑运算符:and、or、not

  • and和&&:俩个条件都为true,结果为true,反之为false
  • || 和 or:只有一个条件为true,结果为true,反之为false
  • | 和 not:如果连接的条件本身为false,结果为true,反之为false;

3、模糊查询

  • like

4、区间查询

between and

5、in

6、is nul

1、按条件表达式筛选

案例:查询员工的工资大于12000

select  * from employees where salary>12000;

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

select 
   last_name,
   department_id
from 
      employees
WHERE
    department_id <> 90 
ORDER BY 
    department_id ;
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;
   not(department_id>= 90 and  department_id<=110) or salary>15000;
3、模糊查询

LIKE :
①:通配符%(任意0和多个字符)使用
②:_任意单个字符

案例1:查询员工名中包含字符a的员工信息;

select  *  FROM employees
where 
   last_name LIKE'%a%';

案例2:查询员工名中第三个字符为n,第五个字符为l的员工名和工资;

select 
  last_name,
  salary
from 
  employees
where 
  last_name like '__n_l%';

案例3:查询员工中第二个字符为 “_ “员工 名(ESCAPE 转义)

select 
   last_name
from 
   employees
where 
   last_name like '_$_%' ESCAPE '$';
4、between and 区间

①:包含临界值
②:两个临界值不可顺序调换

案例1:查询员工编号在100到120之间的员工信息;

select   *  
from 
   employees
where 
   employee_id between 100 and 120;
5、in 判断字段值
  • 作用:判断某字段的值是否属于in列表中的某一项
  • 特点:提高简洁度;in列表的值类型必须一致或兼容;不支持通配符

案例1:查询员工的工种编号为IT_PROG、AD_VP、AD_PRES中的一个员工名和工种编号

select
	last_name,job_id
from 
    employees
where 
    job_id = 'IT_PROG' or job_id = 'AD_VP' or job_id = 'AD_PRES';
=====================================================================
select
      last_name,
     job_id
from 
    employees
where 
     job_id in ('IT_PROG','AD_VP','AD_PRES');
4、is null 判断null值
  • = 或 <> 不能用于判断null值
  • is null 或 is not null 可以用于判断null值

案例1:查询没有奖金的员工名和奖金率

select 
   last_name,
   commission_pct
FROM
    employees
WHERE
    commission_pct is not null; 
    #commission_pct == null;错误
    #commission_pct is null;
    
6、安全等于 <=>

案例1:查询没有奖金的员工名和奖金率

select 
   last_name,
   commission_pct
FROM
    employees
WHERE
  commission_pct <=> null;

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

select 
   *  
from 
	employees
WHERE
	salary <=> 12000;
7、is null PK <=>
  • is null 或 is not null 仅仅用于判断null值,可读性较高
  • <=>:既可以判断NULL值,又可以判断普通的数值;
原文地址:https://www.cnblogs.com/yyb6/p/14181575.html