mysql 条件查询、逻辑查询、模糊查询、通配符、转义字符
程序员文章站
2024-03-01 17:09:58
...
通配符不等代表null
条件查询
select 查询列表 from 表名 where 筛选条件;
分类:
按条件表达式筛选 =,!=
按逻辑表达式筛选 and or not
模糊查询 like、between and、in、is null
查询工资大于12000的员工信息
SELECT * FROM employees WHERE salary >12000;
查询部门编号不等90的员工名和部门编号,要查询的编号
SELECT last_name,department_id FROM employees WHERE department_id <>90;
按逻辑表达式筛选
查询工资在10000到20000之间的员工名、工资以及奖金
SELECT last_name ,salary,commission_pct FROM employees WHERE salary<20000
AND salary>10000;
查询部门编号不是在90到110之间,或者工资高于15000的员工
SELECT
*
FROM employees
WHERE department_id <90
OR department_id >110
OR salary>15000;
#或者
SELECT *
FROM employees
WHERE NOT(department_id>=90 AND department_id<=110) OR salary>15000;
#查找员工姓名和工资不在8000到17000,且按工资升序排列
SELECT
last_name,
salary
FROM
employees
WHERE
salary NOT BETWEEN 8000 AND 17000
ORDER BY
salary ASC;
模糊查询
like,查询员工名中包含字符a的员工信息
SELECT
*
FROM
employees
WHERE
last_name LIKE '%a%'; //百分号%是通配字符,代表其他任意多个字符,_代表任意一个字符
案例:查询员工名中第三个字符为e,第五个字符为a的员工名和工资
SELECT
last_name,
salary
FROM employees
WHERE
last_name LIKE '__e_a%'; //2个下划线+e+一个下划线+a
案例:查询员工名中第二个字符为_的员工名,正常转义字符\
SELECT
last_name
FROM
employees
WHERE
last_name LIKE '_\_%';
自定义转义字符
SELECT
last_name
FROM
employees
WHERE
last_name LIKE'[email protected]_%' ESCAPE '@';