数据库知识整理<四>

使用DML语句更改数据:


所谓DML语句是指数据库操作语句,其中包括的是对数据库数据的修改、删除、插入。

4.1添加新数据:

  1. 插入单行的记录:基本的SQL语句为-insert into <表明>(<列明列表>) values (<值列表>);插入多行记录时中间用逗号隔开。
  2. 还有一种插入方式就是插入其他表的数据时,我们可以使用:insert into <表明>(<列明列表>) select <select语句>;如:insert into student1 (studentID,studentName) select studentId+2,studentName from student2;意思为向student1表中插入student2表中的数据并且student表中的Id都+2开始。因为student1表中已经存在2条记录了。
  3. 表数据的复制,之前有总结过此类的使用方法:select <列明> into <新表名> from <表名>;如:select * into student2 from
  4. student1;意思为:将student1的数据复制到新建的表student2表中。 

4.2更改表中已有的数据:

  1. 更改单列数据:update <表名> set <新列值列表> where <过滤条件>;
  2. 更改多行列数据:在上面的规则上用逗号隔开。
  3. 通过更新删除列中的数据:也就是设置某个字段为空即可。如:update set name = null where id=1;

4.3删除数据:

  1. 使用delete删除数据:delete from <表名> where <过滤条件>;如果不使用过滤条件将是整个行被删除掉。注意delete不能删除某个字段,只能整行删除,要删除某个字段只能update为null,如果有外键约束的话那么先要删除外键。
  2. 使用truncate语句删除:truncate table<表名>;truncate被优化执行起来比delete要快,此删除是不可回滚的,数据将永久性被删除,但是表的结构、列、约束等不会被改动。
  3. truncate table 不能用于有外键约束的表,这种情况下使用delete where 来操作。使用truncate主要可以用于测试数据被删除,将数据库恢复到原始的无数据设计状态。

总结:数据库数据删除的两种方式经常会被问到,因为涉及到数据库的其他操作语句比较简单,只有删除还有两种方式。所以尤为记住truncate table 的删除方式和特点以及弊端。

原文地址:https://www.cnblogs.com/tyhJava/p/5582579.html