資料庫學習5操縱表

2021-08-19 23:07:34 字數 2260 閱讀 8108

操縱表的操作包括對錶的建立、更新和刪除。另外這裡也講講對檢視的使用。

一、建立表

建立表要使用create table關鍵字。

create table customers (

cust_id int not null auto_increment,

cust_name char (50) not null,

cust_address char(100) null,

cust_*** int not null default 1,

primary key (cust_id, cust_name)

) engine = innodb;

表名緊跟在create table關鍵字後面。實際的表定義(所有列)括在圓括號之中。各列之間用逗號分隔。每列的定義以列名(它在表中必須是唯一的)開始,後跟列的資料型別。表的主鍵可以在建立表時用primary key關鍵字指定,當然也可以用逗號,建立乙個多列的主鍵。主鍵不能是都能為null的列。null即允許缺值,not null即不允許。auto_increment告訴mysql,本列每當增加一行時自動增量。每次執行乙個insert操作時, mysql自動對該列增量,給該列賦予下乙個可用的值。default允許指定預設值。

要注意的是,mysql與其他dbms不一樣,它具有多種引擎。它打包多個引擎,這些引擎都隱藏在mysql伺服器內,全都能執行create table和select等命令。為什麼要發行多種引擎呢?因為它們具有各自不同的功能和特性,為不同的任務選擇正確的引擎能獲得良好的功能和靈活性。

二、更新表

其實所謂更新表,就是對錶的結構進行改變,無非就是對列進行更改。要使用alter table語句。

1、新增乙個列

alter table vendors add vend_phone char(20);

2、刪除乙個列

alter table vendors drop colum vend_phone;

三、刪除表(刪除的是整個表,而不是整個表的內容)

刪除表使用drop table語句,很簡單。

drop table customers;

四、重新命名表

用rename table語句。

rename table customers2 to customers, vendors2 to vendors, products2 to products;

五、使用檢視

檢視是乙個虛擬的表,他在實際資料庫中並沒有物理存在。檢視一般包含了乙個sql查詢。使用檢視有很大的意義:

重用sql語句;

簡化複雜的sql操作。在編寫查詢後,可以方便地重用它而不必知道它的基本查詢細節;

使用表的組成部分而不是整個表;

保護資料。可以給使用者授予表的特定部分的訪問許可權而不是整個表的訪問許可權;

更改資料格式和表示。檢視可返回與底層表的表示和格式不同的資料。

在檢視建立之後,可以用與表基本相同的方式利用它們。可以對檢視執行select操作,過濾和排序資料,將檢視聯結到其他檢視或表,甚至能新增和更新資料。重要的是知道檢視僅僅是用來檢視儲存在別處的資料的一種設施。檢視本身不包含資料,因此它們返回的資料是從其他表中檢索出來的。在新增或更改這些表中的資料時,檢視將返回改變過的資料。注意,別檢視更新檢視,這樣很不好。一般檢視都是用來查詢的。

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;

這條語句建立乙個名為productcustomers的檢視, 它聯結三個表。後面如果要使用這個檢視,就可以直接如下:

select cust_name, cust_contact from  productcustomers where prod_id = 'tnt2';

參考資料《mysql必知必會》

資料庫學習 SQL的資料操縱(DML)

常用的資料操縱dml關鍵字 insert delete update insert有兩種形式 1 插入單個元組 insert into 表名 屬性名清單 values 元組值 insert into s xh,xm,xb,csrq,jg,sjhm,yxh values 1101 李明 男 1993 ...

資料庫操縱語言DML

資料庫操縱語言dml dml 有三條語句 insert update delete.一 insert 插入資料 1 插入一條資料 insert into 表名 列名 values 值列表 insert into stuinfo stuname,stuno,stu stuage,stuaddress ...

DML 資料庫操縱語言

增 插入 1,張三,18 注意 字串和日期時間 必須加上 插入完整記錄 insert into student values 1,張三 18 插入部分記錄 insert into student name,age values 張三 18 插入多條完整記錄 insert into student v...