PostgreSQL 复制数据(尝试复制不符合 WHERE 条件的数据)

PostgreSQL Copying Data (tries to copy data that do not qualify WHERE)

当我尝试从我的临时 table Tperson 复制数据时,它会尝试复制所有数据,并且某些数据在 Customer.PersonID 中没有匹配的 PersonID。

DROP TABLE IF EXISTS Tperson;

COPY Customer (CustomerID,PersonID) FROM 'C:\Users\DieCriminal\Desktop\data\Customer.txt' CSV HEADER;

CREATE TEMPORARY TABLE Tperson(PersonID integer,Title text,FirstName text,LastName text);
COPY Tperson FROM 'C:\Users\DieCriminal\Desktop\data\Person.txt' CSV HEADER;

INSERT INTO Customer (Person.PersonID,Person.Title,Person.FirstName,Person.LastName)
SELECT Tperson.PersonID,Tperson.Title,Tperson.FirstName,Tperson.LastName 
From Tperson,Customer
WHERE Customer.PersonID = Tperson.PersonID;

SELECT *
FROM Customer;

所以结果是这样的:

ERROR:  null value in column "customerid" violates not-null constraint
DETAIL:  Failing row contains (null, null, (291,Mr.,Gustavo,Achong,)).
********** Error **********

ERROR: null value in column "customerid" violates not-null constraint
SQL state: 23502
Detail: Failing row contains (null, null, (291,Mr.,Gustavo,Achong,)).

这里还有 Tables/Types: (部分table/types会在加载数据后发生变化)

CREATE TABLE Customer(
CustomerID integer,
PersonID integer,
Person PersonType,
PRIMARY KEY(CustomerID));

CREATE TYPE PersonType AS(
PersonID integer, 
Title text,
FirstName text,
LastName text,
Address AddressType[]);

CREATE TYPE AddressType AS(
AddressID integer,
AddressLine1 text,
AddressLine2 text,
City text,
PostalCode text);

我希望它只复制在两个 tables.That 中都具有匹配 personID 的数据,我认为 WHERE 子句会这样做,但事实并非如此。 所以欢迎任何关于我的代码的回答或任何suggestion/tip。

所以看来我现在很愚蠢并且厌倦了阅读。 我忘记了 INSERT 适用于新行,我需要更新因为我需要更改现有行。

效果很好:

DROP TABLE IF EXISTS Tperson;

COPY Customer (CustomerID,PersonID) FROM 'C:\Users\DieCriminal\Desktop\data\Customer.txt' CSV HEADER;

CREATE TEMPORARY TABLE Tperson(PersonID integer,Title text,FirstName text,LastName text);
COPY Tperson FROM 'C:\Users\DieCriminal\Desktop\data\Person.txt' CSV HEADER;

UPDATE Customer 
SET (Person.PersonID,Person.Title,Person.FirstName,Person.LastName) = (Tperson.PersonID,Tperson.Title,Tperson.FirstName,Tperson.LastName) 
From Tperson
WHERE Customer.PersonID = Tperson.PersonID;

SELECT *
FROM Customer;

感谢:a_horse_with_no_name,他基本上解决了我的 problem.Thanks.