基础查询
基础查询
语法:
select 查询列表 from 表名;
特点:
1、查询列表可以是:表中的字段、常量值、表达式、函数
2、查询结果是一个虚拟的表格
#1.查询表中的单个字段
SELECT last_name FROM employees;
#2.查询表中的多个字段
SELECT last_name,salary,email FROM employees;
#3.查询常量值
SELECT 100;
SELECT 'john';
#4.查询表达式
SELECT 100%9;
#5.查询函数
SELECT VERSION();
#6.为字段起别名
1.便于理解
2. 区分重名的字段
#方式1
SELECT 100%98 AS 结果;
SELECT last_name As 姓,first_name As 名 FROM employees;
#方式2
SELECT last_name 姓,first_name 名 from employees;
#示例 查询salary ,显示结果为 my money
select salary AS "my money" from employees;
#7去重
#示例:查询员工表中涉及到的所有部门编号
select DISTINCT department_id FROM employees;
#8. +号的作用(运算符)
select 100+90; 两个操作数都为数值型,则做加法运算
select'123'+90;其中一个为数值型,试图将字符型转换为数值型,如果转换成功,则继续做加法运算
select 'jhon'+90; 如果字符型无法转换为数值型,则将字符型数值转换为0;
select null+90; 只要其中一方为null,结果肯定为null
#9.字段拼接
#示例:查询员工名和姓连接成一个字段,并显示为姓名
select CONCAT(last_name,first_name) AS 姓名 from employees;
#函数 IFNULL(字段名,值)
#示例:判断如果 字段commission_pac的值为null,将其值作为0;
SELECT IFNULL(commission_pct,0) as 示例 , commission_pct 原本结果 FROM employees;
条件查询
语法:
select
查询列表
from
表名
where
筛选条件;
分类:
1、按条件表达式筛选
条件运算符:>,<,=,!=,<>,>=,<=
2、按逻辑运算符
逻辑运算符:&&,||,!,and ,or ,not
3.模糊运算符
like ,between , and , in , is null
#一、按条件表达式
#示例1:查询工资大于10000的员工信息
select * from employees where salary>10000;
#示例2:查询部门编号不等于90的员工名和部门编号
select last_name, department_id from employees where department_id<>90;#也可以写为artment_id!=90
二、按逻辑表达式
#示例1:查询工资在10000到20000的员工名,工资。以及奖金
select last_name,salary,commission_pct from employees where salary>=10000 and salary <=20000;
#三、模糊查询
like
1.一般和通配符搭配使用
通配符:
%,任意多个字符,包含0个字符
_,任意单个字符
between and
两个临界值不能颠倒
in
1.判断某字段的值是否属于in列表中的某一项
2.in列表中的值的类型 必须一致或兼容
is null
1.=或者<>或者!=不能用于判断 null值
2. is null 活is not null 可以判断 null值
<=>
1.可用于判断null值
2.也可以用于判断普通数值
#示例1: 查询员工名中包含字符a的员工信息
select * from employees where last_name like '%a%'; #两个%代表通配符,表示任意一个位置有a都可以
#示例2:查询员工名中第三个字符为额,第五个字符为啊的员工名和工资
select last_name,salary from employees where last_name like '__e_n%';
#示例3:查询员工名中第二个字符为_的员工名和工资
select last_name,salary from employees where last_name like '_\_ %';#通过转义字符\实现(***这里博客显示有问题看图片***)
#或者通过关键词 escape
select last_name,salary from employees where last_name like '_#_%' escape '#';#其中符号#可以任意写一个,但是相应escape后面的也要写成一样的。如 '_$_%' escape '$'
#示例4:between and
#查询员工编号在90到120之间的员工信息
select * from employees where employee_id between 100 and 120;
#示例5:in
#查询员工的工种编号是 IT_PROG、AD_VP、AD_PRES中的一个员工和工种编号
select last_name,job_id from employees where job_id in ('IT_PROG','AD_VP','AD_PRES');
#示例6:is null
#查询没有奖金的员工名和奖金
select last_name,commission_pct from employees where commission_pct is null;
#示例7:<=>安全等于
#查询没有奖金的员工名和奖金
select last_name,commission_pct from employees where commission_pct<=>null;