数据库(八)——创建和操纵表、使用视图

80 阅读1分钟

一、创建表

利用create table创建表

  1. 新表名字没在关键字create table之后给出;
  2. 表列的名字和定义,用逗号分隔;
  3. 有的DBMS还要求指定表位置
CREATE TABLE Customers
(
  cust_id      char(10)  NOT NULL ,
  cust_name    char(50)  NOT NULL ,
  cust_address char(50)  NULL ,
  cust_city    char(50)  NULL ,
  cust_state   char(5)   NULL ,
  cust_zip     char(10)  NULL ,
  cust_country char(50)  NULL ,
  cust_contact char(50)  NULL ,
  cust_email   char(255) NULL 
); 

Null值是没有值,不是空字符串。空字符串是一个有效的值,它不是无值。

  1. 指定默认值
    默认值在create table语句的列定义中用关键字default指定。默认值经常用于日期或时间戳列。

更新表

给已有表增加列

alter table Vendors add vend_phone char(20);

删除表

Drop table CustCopy;

二、使用视图

  1. 作为视图,它不包含任何列或数据,包含的是一个查询。
create view ProductCustomers as select cust_name,cust_contact,prod_id from Customers,Orders,OrderItems where Customers.cust_id = Orders.cust_id and
OrderItems.order_num = Orders.order_num;
select cust_name,cust_contact from ProductCustomers where prod_id = 'RGAN01';
  1. 用视图重新格式化检索出的数据
create view VendorLocations as select RTRIM(vend_name)+'('+ RTRIM(vend_country)+')' as vend_title From Vendors; 
  1. 用视图过滤不想要的数据
create view CustomerEMailList as select cust_id,cust_name,cust_email from Customers where cust_email is not null;
  1. 使用视图与计算字段
create view orderItemsExpanded as select prod_id,quantity,item_price,quantity*item_price as expanded_proce from OrderItems;