我是SQL Oracle的新手。我正在尝试“合并”两个表。
PAYMENT_COMMON ---> TABLE A
(PCO_NUMBER(6,0) NOT NULL,
ID_BUILD NUMBER(5,0) NOT NULL,
NUM_DEPARMENT NUMBER(5,0) NOT NULL,
PGC_DATE_CANCELATION DATE NOT NULL,
PGC_AMMOUNT_PAY NUMBER(10) NOT NULL,
ID_VIA_PAYMENT NUMBER(2,0) NOT NULL);
和一个名为payment_common1的表(与payment_common相同的行和列),其中有111个不在PAYMENT_COMMON
中的值。
因此,我尝试使用查询添加这些值,而不重复这些值:
INSERT INTO PAYMENT_COMMON(PCO_NUMBER,
ID_BUILD NUMBER,
NUM_DEPARTMENT,
PGC_DATE_CANCELATION,
PGC_AMMOUNT_PAY,
ID_VIA_PAYMENT)
SELECT * FROM PAYMENT_COMMON
UNION
SELECT * FROM PAYMENT_COMMON1;
但返回
ORA-00001: unique constraint (SYSTEM.PK_PAYMENT_COMMON) violated
希望有人可以帮助我找出我的错误。
答案 0 :(得分:0)
您应检查组成主键索引的哪些列(PK_PAYMENT_COMMON)。通过以下语句执行此操作:
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cols.table_name = 'PAYMENT_COMMON'
AND cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;
但是您的INSERT
语句的主要问题是PAYMENT_COMMON
表中已经存在行,因此不需要再次插入它们。
另外,执行DML语句(INSERT
,UPDATE
或DELETE
时,显式比隐式更好。因此,请避免使用SELECT *
并指定所有列。如果表结构发生更改,这有助于避免意外错误。
假定PCO_NUMBER
是主键(根据上面的结果更改WHERE
语句中的EXISTS
子句),查询应为以下内容:>
INSERT INTO PAYMENT_COMMON
(
PCO_NUMBER,
ID_BUILD,
NUM_DEPARTMENT,
PGC_DATE_CANCELATION,
PGC_AMMOUNT_PAY,
ID_VIA_PAYMENT
)
SELECT
PCO_NUMBER,
ID_BUILD,
NUM_DEPARTMENT,
PGC_DATE_CANCELATION,
PGC_AMMOUNT_PAY,
ID_VIA_PAYMENT
FROM PAYMENT_COMMON1 C1
WHERE NOT EXISTS (
SELECT 1
FROM PAYMENT_COMMON C
WHERE C.PCO_NUMBER = C1.PCO_NUMBER
);