文章目錄
插入完整的行:values子句
不安全寫法
insert into Customers
values('1000000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA',
NULL,
NULL);
總之就是次序很重要,但是次序很容易輸入出錯,所以這樣寫不安全
安全寫法:在表名後的括號明確給出列名
也更繁瑣,有個明確的對應關係,出錯的概率就小很多
insert into Customers(cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email)
values('1000000006',
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA',
null,
null);
由於我前面已經插入了這一行,所以這次插入同樣的數據,出錯了,但是代碼本身沒錯哦
這種寫法,可以換values列表的輸入次序,只要把前面表名後括號中的項的順序也改一改就好了,保證對應關係正確
insert into Customers(cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
values('1000000006',
null,
null,
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA');
當然還是報duplicate entry錯誤啦
小結
- 不要用第一種不安全寫法,因爲表結構一旦變化,前面的代碼就都完犢子。。。
- 不管用第一種還是第二種,最起碼的一點一定要保證:values列表的值的數目是對的,這樣纔是提供完整一行呀。否則就會出錯。
插入行的一部分:簡單
即只給某些列提供值,其他列不給值就行了。但是必須保證不給值的那些列允許是null值或者有默認值纔可以
insert into Customers(cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state)
values('1000000006',
null,
null,
'Toy Land',
'123 Any Street',
'New York',
'NY');
當然還是報duplicate entry錯誤啦
插入某些查詢的結果(即檢索出的數據):insert select
示例:把另一個表的某幾列合併到一個表中
示例代碼
insert into Customers(cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
select cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country
from CustNew;
這個代碼會報錯,因爲我們的數據庫沒有CustNew這個表。但是不影響學習這個知識
- insert select可以用一個select語句插入多行
- 不要求insert into後表名括號中的列名和後面select後的列名一樣,因爲DBMS操作的是列的位置,列名只是給出位置而已,他可以正確解析。
- insert select中的select語句可以包含where子句。
從一個表複製到另一個表:select into語句(不用insert語句實現數據的插入)
- select into語句完全和insert無關,但也是用於實現數據插入的
- select into 語句把數據導入到的新表是運行時創建的,之前並不存在
- 而insert select是把一個表中導出的數據導入到另一個之前就存在的表。
示例
select *
into CustCopy
from Customers;
mysql不支持這種語法。。。
它要這麼寫:
CREATE table CustCopy as
select * from Customers;
但我覺得還是select into更好,很易懂
小結
- select inro可以用很多select選項,但是我這裏用mysql不支持這種語法也沒法做實驗
- 可以用聯結從多個表插入數據,我覺得這個很難,兩個複雜功能一起用,,,
- 數據可以來自多個不同的表,但是去向只有一個,只能被插入到一個表
總結
關鍵字
- into
- values
- select into:把行導入到一個新表
- insert select:從其他表導入行
- create table