update語句
- 一定要用where子句過濾出你想更新的行,千萬不要更新所有行,就這點容易出錯,所以使用updata語句的權限要求更高。畢竟90%的人用數據庫只能查,根本不能添刪改。
- 而update語句本身是特別簡單的,所以難點就是過濾出想更新的行。
示例1:更新一列
UPDATE Customers
set cust_email = '[email protected]'
where cust_id = '1000000005';
用select語句查一下修改後的結果
select cust_id, cust_name, cust_email
from Customers
where cust_id = '1000000005';
示例2:更新多列
update Customers
SET cust_contact = 'Sam Robert',
cust_email = '[email protected]'
where cust_id = '1000000006';
更新後查詢:
select cust_id, cust_name, cust_contact, cust_email
from Customers
where cust_id = '1000000006';
示例3:通過設置某個值爲null,以刪除它
update Customers
set cust_email = null
where cust_id = '1000000005';
查詢
select cust_id, cust_name, cust_contact, cust_email
from Customers
where cust_id = '1000000005';
小結
- 更新一列或者多列都只需要一個set命令
- 在updata語句中可以用子查詢,以用查詢出的數據更新,而不必自己輸入。
我想自己試試怎麼寫的,然後寫了下面的代碼,雖然執行正確沒報錯,但是並沒有真的改成功。
update Customers
set cust_email = (select cust_email where cust_id = '1000000001')
where cust_id = '1000000005';
注意上面的括號中不可以寫from Customers,不然報錯。
select cust_email from Customers where cust_id = '1000000001'
所以我還是不知道怎麼在update中用子查詢。。。一個失敗的嘗試
- 在update中使用from子句
這個嘗試也失敗了
CREATE table CustCopy as
select * from Customers;
update CustCopy
set CustCopy.cust_email = '[email protected]'
where CustCopy.cust_id = '1000000004';
update customers from CustCopy
where Customers.cust_id = '1000000004';
本意是:創建一個新表CustCopy,它和customers表一樣,然後先修改一下custcopy表的一個email地址,然後再用custcopy去更新customers表。
看來是因爲mysql語法的問題,暫時不想深究了
delete語句
和update的注意點一樣
示例1
delete from Customers
where cust_id = '1000000006';
小結
- 一定要定義外鍵:以防止刪除某個關係要用到的行
- delete刪除的是一整行。所以如果你想刪除某一列,就要用update語句,搭配null。
- delete語句刪除的是表的行,不會刪掉表本身。
- 刪除表的所有行,又不用delete了,不是做不到,而是速度不夠快。應該用truncate table語句,(之前用過create table語句創建表)速度更快。
- 每個表都必須有主鍵
- 一定一定要用where子句,並且還必須先用select測試一下where子句的過濾條件的正確性,然後再去更新或者刪除,不然沒有撤銷後悔藥,會完犢子的。
- 總之就是小心小心再小心,從刪庫到跑路,很危險的
總結
where子句對update和delete語句是非常非常非常重要的。
關鍵字
- update
- set
- delete
- truncate table