暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

openGauss每日一练第13天 | 数据导入的操作

原创 田灬禾 2021-12-14
499

今天学习数据的导入,该操作日常也是用的比较多。

学习笔记:

  • 表字段默认值:跟oracle区别的是,可以插入的时候指定default关键字;

这边说下语法比较不一样:

ALTER TABLE <table> ALTER COLUMN <column> SET DEFAULT 'XXX';
ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;
复制

整行一个默认值插入:

insert into <table> DEFAULT VALUES;
复制
  • 使用COPY命令的拷贝

copy <table> to stdout; --将表数据输出到stdout
复制
copy <table> to '/xxx/xx/xxx.dat';  --将表数据拷贝到文件
复制
copy reason_t3 from '/home/omm/reason.dat'; --将数据从文件拷贝到表
复制
  • 创建表
CREATE TABLE <table1> (LIKE <table2> );
复制

当然也支持 创建并复制数据

CREATE TABLE <table1>  as select * from <table2>;
复制

课后练习:

1.创建表1并在表中插入数据,分别指定字段和整行为缺省值

openGauss=# create table t (id int,name char(30) default 'XXX');
CREATE TABLE
openGauss=# insert into t values (1,'a'),(1);
ERROR:  VALUES lists must all be the same length
LINE 1: insert into t values (1,'a'),(1);                                 ^
openGauss=# insert into t values (1,'a'),(1,default);
INSERT 0 2              ^
openGauss=# insert into t default values;
INSERT 0 1
openGauss=# select * from t;
 id |              name              
----+--------------------------------
  1 | a                             
  1 | XXX                           
    | XXX                           
(3 rows)
复制


2.创建表2并将表1的数据全部导入表2中

openGauss=# create table t2 (like t);
CREATE TABLE
openGauss=# insert into t2 select * from t; INSERT 0 3 openGauss=# select * from t2; id | name ----+-------------------------------- 1 | a 1 | XXX | XXX (3 rows)
复制


3.创建表3和表4,并合并两个表的数据到表3

openGauss=# create table t3(a int,b int);
CREATE TABLE
openGauss=# insert into t3 values(1,1),(2,2);
INSERT 0 2
openGauss=# create table t4(a int,b int);
CREATE TABLE
openGauss=# insert into t4 values(3,3),(4,4);
INSERT 0 2                    ^
openGauss=# merge into t3 using t4 on (t3.a=t4.a) when matched then update set t3.b=t4.b when not matched then insert values(t4.a,t4.b);
MERGE 2
openGauss=# select * from t3;
 a | b 
---+---
 1 | 1
 2 | 2
 3 | 3
 4 | 4
(4 rows)

openGauss=# 
复制


4.将表3的数据输出到文件,再将文件中的数据导入到表5

openGauss=# copy t3 to '/home/omm/t3.dat';
COPY 4
openGauss=# create table t5 (like t3);
CREATE TABLE
openGauss=# copy t5 from '/home/omm/t3.dat';
COPY 4
openGauss=# select * from t5;
 a | b 
---+---
 1 | 1
 2 | 2
 3 | 3
 4 | 4
(4 rows)
复制


「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论