Oracle

在 Oracle 表中僅插入第一次出現

  • June 23, 2020

我有一張桌子


CREATE TABLE PEOPLE
(
NAME VARCHAR(64 BYTE)PRIMARY KEY NOT NULL,
TIME TIMESTAMP(6),
NICKNAME VARCHAR2(16 BYTE),
STATE VARCHAR2(50 BYTE),
CITY VARCHAR(128 BYTE)
)

我想從其他表中插入此表中的值,但是對於列 NAME,引用表可以有重複的 NAME,在我的 TABLE PEOPLE 中,我希望它只插入第一次出現的 NAME,並在它已經存在時丟棄。

我試過這個


INSERT 
INTO PEOPLE( NAME, TIME,NICKNAME, STATE)
SELECT 
DISTINCT p.NAME,
p.TIME,
l.NICKNAME,
pt.STATE
from PBO p
LEFT JOIN PASST pt ON pt.NAME = p.NAME 
LEFT JOIN LIEN l ON l.NAME = p.NAME 
WHERE not exists (
   select * from PEOPLE f
   where  f.NAME= pt.NAME
 )
AND
p.TIME> '25/05/20 00:00:00'
order by p.TIME desc

但我仍然收到 oracle 錯誤:Duplicate Key Errors (ORA-00001)。

感謝任何幫助

MERGE INTO PEOPLE e using 
(SELECT 
DISTINCT p.NAME,
p.TIME,
l.NICKNAME,
pt.STATE
from PBO p
LEFT JOIN PASST pt ON pt.NAME = p.NAME 
LEFT JOIN LIEN l ON l.NAME = p.NAME 
WHERE not exists (
   select * from PEOPLE f
   where  f.NAME= pt.NAME
 )
AND
p.TIME> '25/05/20 00:00:00') d
on (e.name = d.name)
WHEN NOT MATCHED THEN
 INSERT  (NAME, TIME,NICKNAME, STATE) VALUES (d.name, d.time, d.nickname, d.state);

或者使用ignore_row_on_dupkey_index提示。

INSERT /*+ ignore_row_on_dupkey_index(people(name)) */
INTO PEOPLE( NAME, TIME,NICKNAME, STATE)
SELECT 
DISTINCT p.NAME,
p.TIME,
l.NICKNAME,
pt.STATE
from PBO p
LEFT JOIN PASST pt ON pt.NAME = p.NAME 
LEFT JOIN LIEN l ON l.NAME = p.NAME 
WHERE not exists (
   select * from PEOPLE f
   where  f.NAME= pt.NAME
 )
AND
p.TIME> '25/05/20 00:00:00'
;

像那樣:

MERGE
INTO PEOPLE( NAME, TIME,NICKNAME, STATE)
SELECT 
DISTINCT p.NAME,
p.TIME,
l.NICKNAME,
pt.STATE
from PBO p
LEFT JOIN PASST pt ON pt.NAME = p.NAME 
LEFT JOIN LIEN l ON l.NAME = p.NAME 
WHERE 
p.TIME> '25/05/20 00:00:00'
order by p.TIME desc

我得到錯誤的 SQL:ORA-02012“缺少 USING 關鍵字”

引用自:https://dba.stackexchange.com/questions/269716