SQL (十五)更新和删除数据(updata语句,delete语句)
文章目录
- update语句
- 示例1:更新一列
- 示例2:更新多列
- 示例3:通过设置某个值为null,以删除它
- 小结
- delete语句
- 示例1
- 小结
- 总结
update语句
- 一定要用where子句过滤出你想更新的行,千万不要更新所有行,就这点容易出错,所以使用updata语句的权限要求更高。毕竟90%的人用数据库只能查,根本不能添删改。
- 而update语句本身是特别简单的,所以难点就是过滤出想更新的行。
示例1:更新一列
UPDATE Customers
set cust_email = 'kim@thetoystore.com'
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 = 'sam@toyland.com'
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 = 'lalala@huhuhu.com'
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
还没有评论,来说两句吧...