12 创建高级联结
12.1 使用表别名
select cust_name, cust_contact
from customers as c, orders as o, orderiterms as oi
where c.cust_id = o.cust_id
and oi.order_num = o.order_num
and prod_id = 'RGAN01';
注:表别名只在查询中使用。与列别名 不一样,表别名不返回到客户端。
12.2 使用不同类型的联结
- 自联结
- 自然联结
- 外联结
12.2.1 自联结
--如,要给与 Jim Jones 同一公司的所有顾客发送一封信件。这个查询要求先找出 Jim Jones 工作的公司,然后找出在该公司工作的顾客。可以用下述方法解决。
select c1.cust_id, c1_cust_name, c1.cust_contact
from customers as c1, customers as c2
where c1.cust_name = c2.cust_name
and c2.cust_contact = 'Jim Jones';
12.2.2 自然联结
标准的联结返回所有数据,相同的列甚至多次出现。自然联结排除多次出现,使每一列只返回一次。
这一般通过对一个表使用通配符(select *),而对其他表的列使用明确的子集来完成。
select C.*, O.order_num, O.order_date, OI.prod_id, OI.quantity, OI.item_price
from Customers as C, Orders as O, OrderItems as OI
where C.cust_id = O.cust_id
and OI.order_num = O.order_num
and prod_id = 'RGAN01';
12.2.3 外联结
外联结:联结包含了那些在相关表中没有关联行的行。
- right / left / full outer join
13 组合查询
union / union all
主要有两种情况需要使用组合查询:
- 在一个查询中从 不同的表返回结构数据
- 对一个表执行多个查询,按一个查询返回数据
13.1 union 规则
- union 中的每个查询必须包含相同的列、表达式或聚集函数(不过,各个列不需要以相同的次序输出)
- 列数据类型必须兼容
13.2 包含或取消重复的行
- union 从查询结果集中自动去除了重复的行
- 如果想返回所有的匹配行,可使用 union all 而不是 union
13.3 对组合查询结果排序
在使用 union 组合查询时,只能使用一条 order by 子句,它必须位于最后一条 select 语句之后。
14 插入数据
14.1 数据插入
- 插入完整的行
- 插入行的一部分
- 插入某些查询的结果
14.1.1 插入完成的行
insert into customers(cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email)
values('100000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA',
NULL,
NULL);
14.1.2 插入部分行
省略的列必须满足以下某个条件:
- 该列的定义为允许 null 值
- 在表定义中给出默认值
14.1.3 插入检索出的数据
insert into customers(cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email
select cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email
from custnew;
注:为了简单,这个例子在 insert 和 select 语句中使用了相同的列名,但是,不一定要求列名匹配。DBMS 使用的是列的位置,因此 select 中的第一列将用来填充表列中指定的第一列,第二列以此类推。
14.2 从一个表复制到另一个表
create table custcopy as
select * from customers;
15 更新和删除数据
15.1 更新数据
update customers
set cust_email = 'kim@thetoystore.com'
where cust_id = '100000005';
15.2 删除数据
使用 delete
16 创建和操纵表
16.1 创建表
create tables products
( --列名 数据类型 是否空值 默认值
prod_id char(10) not null default x ,
prod_desc text(1000) null
);
16.2 更新表
alter table vendors
add vend_phone char(20); --添加列
alter table vendors
drop column vend_phone; --删除列
16.3 删除表
drop table
16.4 重命名表
rename
17 使用视图
- 视图是虚拟的表
- 视图不包含数据,每次使用视图时,都必须处理查询执行时所需要的所有检索
- 视图必须唯一命名