2021.10.26
SQL SELECT语句
DML:Data Manipulation Language数据操纵语言
INSERT:增
UPDATE:改
DELETE:删
SELECT:查
DDL:Data Definition Language数据定义语言
CREATE TABLE:创建数据库表
ALTER TABLE:更改表结构、添加、删除、修改列长度
DROP TABLE:删除表
CREATE INDEX:在表上建立索引
DROP INDEX:删除索引
DCL:Data Control Language数据控制语言
GRANT:授予访问权限
REVOKE:撤销访问权限
COMMIT:提交事务处理
ROLLBACK:事务处理回退
SAVEPOINT:设置保存点
LOCK:对数据库的特定部分进行锁定
SELECT
选择全部
select * from employees;
选择部分列
select employee_id,last_name,email
from employees;
算数运算符
数字和日期可以使用算数运算符加减乘除
select last_name,salary,12*salary + 1000
from employees;
sysdate
可以用于获取当前时间
select sysdate from dual;
列的别名
通过在列后增加空格及需要命的名来更改查询后显示的列名
select employee_id id,last_name name,12*salary annual_sal
from employees;
也可以通过添加as进行实现
select employee_id as id
from employees;
上述会将字母默认大写
如需小写,可以通过双引号实现
select employee_id as "id";
连接符’||’
select last_name||'`s job_id is '||job_id as details
from employees;
SQL中字符串用单引号包围
distinct关键字
默认情况下select会返回所有记录,包括重复行,添加distinct可以去除重复
select distinct department_id from employees
SQL与SQL*PLUS
desc employees;
查看表employees中的所有信息
该语句为缩写,即SQL语句为describe employees
注意事项
1.SQL语言大小写不敏感,并可以写在多行中,但关键字不可换行
2.空值为空,并不被赋予0作为初始值,即不可直接计算
3.日期中乘法,除法是不合法的
总结
1.select语句可应用于查看所有表
2.查看指定表
3.使用别名
习题
过滤和排序
where关键字
基本使用方式
select employee_id,last_name,salary
from employees
where last_name = 'Higgins'
注意,其中字符串内容严格区分大小写,并且select和where中的列都必须存在。
由于本地化的方式,下图方法并不可以搜索日期的值
需要改为使用
上述方法在引入单行函数后也被舍弃
可用的比较运算操作符
between and
包含边界值
select last_name,hire_date,salary
from employees
where salary between 4000 and 7000
in(x,y,z)
变量等于x或y或z
select last_name,hire_date,salary
from employees
where department_id in(70,80,90)
like
模糊查询
like ‘字符’:模糊查询满足’字符’条件的值
1.%
%表示零个或多个任意字符
select last_name,hire_date,salary
from employees
where last_name like '%a%'
--名字中含有a的员工
2._
_表示单个字符
select last_name,hire_date,salary
from employees
where last_name like '_a%'
--第二位是a的员工
3.转义符
上述方法无法查询到包含_或%的字符,因此要加入转义符
select last_name,hire_date,salary
from employees
where last_name like '%#_a%' escape '#'
--查看包含_a字段的员工名
其中#可以换为任意字符,只需在escape后定义即可
is null
查询空值
select last_name,department_id,salary,commissiong_pct
from employees
where commission_pct is null
select last_name,department_id,salary,commissiong_pct
from employees
where commission_pct is not null
--查询非空的值
逻辑运算
直接在where中添加即可
优先级
order by
添加在select语句的结尾即可
1.asc(ascend)升序
2.desc(descend)降序
select last_name,department_id,salary
from employees
where department_id = 80
order by salary desc
可以实现多重排序
select last_name,department_id,salary
from employees
order by salary asc,order by last_name asc
--先按照salary进行排序,再按照名字进行排序
也可以按照别名进行排序
总结
1.where语句用于过滤数据
使用比较运算
使用between and, in, like, is null运算
使用逻辑运算符
2.order by可用于排序
习题