SQL 更新实例

插入

  • 插入默认值
-- 数据准备
create table table4(
  id int4,
  name text default 'no one'
);
-- 使用 default
insert into table4 values (1001, default);
insert into table4(id) values (1002);
  • 多表插入
-- 数据准备
create table raw_data(
  id int,
  name varchar2(32),
  dept varchar2(32),
  salary double precision
);
insert into raw_data values (1001, 'aladdin', 'bigdata', 13000);
insert into raw_data values (1002, 'bilib', 'java', 10000);
-- 创建相似表结构,无法使用 like
create table med_emp_info as select * from raw_data where 1 = 0;
create table hig_emp_info as select * from raw_data where 1 = 0;

-- Oracle 支持,MySQL 和 Postgres 不支持
-- 多表插入
insert all
  when
    salary <= 10000
  then
    into med_emp_info(id, name, dept, salary)
    values (id, name, dept, salary)
  when
    salary > 10000 and salary <= 30000
  then
    into hig_emp_info(id, name, dept, salary)
    values (id, name, dept, salary)
select id, name, dept, salary
from raw_data;

复制数据

  • 复制数据到另一个表
insert into table6 select * from table5;
  • 复制表结构
-- MySQL/Postgres/Oracle
create table table6 as select * from table5 where 1 = 0;
-- DB2
create table table6 like table5;

更新

  • 更新记录
update table5 set name = 'chrome' where id = 1002;
update table5 set name = 'ccc' where emp in (select emp from emp_bonus);
  • 使用另一表的数据更新
-- Oracle
update
  table1 t1
set 
    (id, salary) = (select id, salary from table2 t2 where t1.id = t2.id)
where exists (select null from table2 t2 where t1.id = t2.id);

-- Postgres
update
  table1 t1
set
    salary = t2.salary
from
     table2 t2
where
      t1.id = t2.id;

删除

  • 删除记录
-- 删除全部数据
delete from table2;
-- 删除指定数据
delete from table1 where id = 1001;
  • 删除违反参照物的数据
-- 使用 exists
delete from
            table1 t1
where not exists(select * from table2 t2 where t1.id = t2.id);
-- 使用 not in
delete from table1 where id not in (select id from table2);
  • 删除重复数据
-- 数据准备
create table table3(
  id int,
  name varchar2(32)
);
insert into table3 (id, name) values (1001, 'a');
insert into table3 (id, name) values (1002, 'b');
insert into table3 (id, name) values (1003, 'c');
insert into table3 (id, name) values (1004, 'c');
insert into table3 (id, name) values (1005, 'c');
-- 删除数据
delete from table3 where id not in (select min(id) from table3 group by name);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,972评论 0 9
  • MYSQL 基础知识 1 MySQL数据库概要 2 简单MySQL环境 3 数据的存储和获取 4 MySQL基本操...
    Kingtester阅读 8,060评论 5 115
  • 爆竹声中一岁除,春风送暖入屠苏。千门万户曈曈日,总把新桃换旧符。”这是宋朝大诗人王安石描写的春节景象,和谐美好,现...
    梁一丹阅读 198评论 0 0
  • 四升级换代阅读 106评论 1 0
  • 2018年5月21日 星期一 多云 521,我爱你,儿子,妈妈真的很爱你,但这种爱却只能放在心底。不想...
    栋钰妈阅读 45评论 0 0

友情链接更多精彩内容