MySQL复习笔记(三):条件查询

条件查询

语法:

select 查询列表 from 表名 where 查询条件
  1. 按照条件表达式筛选:简单条件表达式:< > = != <> >= <=
SELECT * FROM employees WHERE salary > 12000;
  1. 按逻辑运算符筛选:&& and || or ! not
#查询工资在10000和20000之间的员工
SELECT last_name,salary,commission_pct FROM employees WHERE salary >= 10000 AND salary <= 20000;
#查询部门id不在90和110之间,或者工资大于15000的员工信息
SELECT * FROM employees WHERE NOT(department_id >=90 and department_id <=110) or salary >15000;
SELECT * FROM employees WHERE department_id < 90 or department_id > 110 or salary >15000;
  1. 模糊查询:like between and in is null

LIKE

#like 用于字符模糊匹配:查询名中带a的员工信息
SELECT * FROM employees WHERE last_name LIKE '%a%';
  • 在SQL语句中字符串必须用要单引号括起来
  • 字符串中的%是通配符,一般和like搭配使用。%代表任意多个字符(包含0个字符)
  • 下划线_代表任意单个字符;
  • like也可以匹配数值型字段
#表示查找名中第2个字符为a,第四个字符为b的员工
select * from employees where last_name LIKE '_a_b%';
#要查询名中第二字符为_的,可以使用\_转义表示字符_
select * from employees where last_name LIKE '_\_%';
#也可以使用关键字ESCAPE指定转义字符,这两个语句效果是一样的
select * from employees where last_name LIKE '_$_%' ESCAPE '$';

between and

# 查询员工id在100和120之间的
SELECT * from employees WHERE employee_id BETWEEN 100 AND 120;
  • between and包含临界值
  • 临界值顺序影响结果

in

# 因表示在某个集合之内,可以替代 = or = ....
SELECT * from employees WHERE employee_id IN (111, 105,130);
  • in列表中的值必须统一或者兼容(‘123’->123)
  • in不支持通配符(本质上是=,不是like)

IS NULL (IS NOT NULL)

# 查询没有奖金率为null的员工名
SELECT last_name, commission_pct FROM employees WHERE commission_pct is null;
# 查询有奖金的员工名
SELECT last_name, commission_pct FROM employees WHERE commission_pct is not null;
  • =和<>不能用来判断null值,只有 is null和is not null可以用来判断null值
  • is和is not不能代替 =和<>

安全等于:<=>

<=>既可以判断null值,也可以判断普通数值

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

练习

1、查询没有奖金,且工资小于18000的员功工salary, last_name

select last_name,salary from employees where commission_pct is null and salary < 18000;

2、查询employees表中,job_id不为‘IT’ 或者工资为12000的员工信息

select * from employees where job_id <> 'IT' or salary = 12000;

3、查看department表表结构

DESC departments;

4、查询department表涉及哪些位置id

SELECT DISTINCT location_id from departments;

5、试问select * from employees;select * from employees where commission_pct like '%%' and last_name LIKE '%%'; 获取的结果是否一样?
答:如果commission_pct字段或 last_name字段中有null则不一样。如果没有则一样。当把and换为or时只有有一个字段不为null就一样

你可能感兴趣的:(后端,MySQL,数据库,mysql,sql)