CUBRID学习笔记 45 REPLACE DELETE MERGE 教程

时间:2023-12-21 23:47:14

c#,net,cubrid,教程,学习,笔记欢迎转载 ,转载时请保留作者信息。本文版权归本人所有,如有任何问题,请与我联系wang2650@sohu.com 。 过错
------ 官方文档是英文的,看不明白可以参看ocracle的同类函数说明.很多都是一样的.

REPLACE
和insert类似,但是他是删除已存在的记录,然后插入.
当存在重复值的时候(主键,唯一所以冲突),不会报错.
CREATE TABLE a_tbl4 LIKE a_tbl1;
INSERT INTO a_tbl4 SELECT * FROM a_tbl1 WHERE id IS NOT NULL and name IS NOT NULL;

SELECT * FROM a_tbl4;
id name phone
=========================================================
1 'aaa' '000-0000'
2 'bbb' '000-0000'
3 'ccc' '333-3333'
6 'eee' '000-0000'
--insert duplicated value violating UNIQUE constraint
REPLACE INTO a_tbl4 VALUES(1, 'aaa', '111-1111'),(2, 'bbb', '222-2222');
REPLACE INTO a_tbl4 SET id=6, name='fff', phone=DEFAULT;

SELECT * FROM a_tbl4;
id name phone
=========================================================
3 'ccc' '333-3333'
1 'aaa' '111-1111'
2 'bbb' '222-2222'
6 'fff' '000-0000'

DELETE
删除一条
DELETE FROM a_tbl WHERE phone IS NULL LIMIT 1;

DELETE FROM a_tbl;删除所有
DELETE a, b FROM a_tbl a, b_tbl b, c_tbl c
WHERE a.id=b.id AND b.id=c.id;

DELETE a, b FROM a_tbl a INNER JOIN b_tbl b ON a.id=b.id
INNER JOIN c_tbl c ON b.id=c.id;

删除多表用using

DELETE FROM a, b USING a_tbl a, b_tbl b, c_tbl c
WHERE a.id=b.id AND b.id=c.id;

DELETE FROM a, b USING a_tbl a INNER JOIN b_tbl b ON a.id=b.id
INNER JOIN c_tbl c ON b.id=c.id;

MERGE
用来合并UPDATE和INSERT语句。通过MERGE语句,根据一张表(原数据表,source table)或子查询的连接条件对另外一张(目标表,target table)表进行查询,连接条件匹配上的进行UPDATE,无法匹配的执行INSERT。这个语法仅需要一次全表扫描就完成了全部工作,执行效率要高于INSERT+UPDATE. 但是为了保证准确,你不能多次更新目标表的相同记录. (不要在一个执行计划中,多次更新目标表的相同记录)

CREATE TABLE source_table (a INT, b INT, c INT);
INSERT INTO source_table VALUES (1, 1, 1);
INSERT INTO source_table VALUES (1, 3, 2);
INSERT INTO source_table VALUES (2, 4, 5);
INSERT INTO source_table VALUES (3, 1, 3);

-- target_table
CREATE TABLE target_table (a INT, b INT, c INT);
INSERT INTO target_table VALUES (1, 1, 4);
INSERT INTO target_table VALUES (1, 2, 5);
INSERT INTO target_table VALUES (1, 3, 2);
INSERT INTO target_table VALUES (3, 1, 6);
INSERT INTO target_table VALUES (5, 5, 2);

MERGE INTO target_table tt USING source_table st
ON (st.a=tt.a AND st.b=tt.b)
WHEN MATCHED THEN UPDATE SET tt.c=st.c
DELETE WHERE tt.c = 1
WHEN NOT MATCHED THEN INSERT VALUES (st.a, st.b, st.c);

-- the result of above query
SELECT * FROM target_table;
a b c
=======================================
1 2 5
1 3 2
3 1 3
5 5 2
2 4 5