简体   繁体   中英

Import data from two tables SQL + PK/FK

I want to insert data from two different tables into this one:

DROP TABLE IF EXISTS Customer CASCADE;
CREATE TABLE Customer (
CustomerID INTEGER,
CompanyName VARCHAR(255),
ContactName VARCHAR(255),
ContactTitle VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
Region VARCHAR(255),
PostalCode VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (CustomerID),
FOREIGN KEY (CustomerID) REFERENCES Person(PhoneID)
);

CustomerID is PK/FK of PhoneID and PhoneID is in the table Person .
The other values are in the table CustomerOrders .

So I want to insert PhoneID into CustomerID and the rest of the data of CustomerOrders in the other variables.

I have proposed this:

  INSERT INTO customer (
     customerid,
     companyname,
     contactname,
     contacttitle,
     address,
     city,
     region,
     postalcode,
     country
)
     SELECT phoneid,
            companyname,
            contactname,
            contacttitle,
            address,
            city,
            region,
            postalcode,
            country
     FROM person,
          customerorders;

But when I compile it says:

[2018-12-17 18:03:26] [23505] ERROR: duplicate key violates uniqueness restriction «customer_pkey»

[2018-12-17 18:03:26] Detail: The key already exists (customerid) = (1).


In case I have not finished explaining well here I leave the model:

模型

Your insert query should have at least one join between both of tables until you don't want to make it cross. Anyway, you are getting the issue because of Inserting customerID already present.

    INSERT INTO Customer(CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country) 
    SELECT PhoneID, CompanyName, ContactName, ContactTitle, Address, City, Region , PostalCode, Country
    FROM Person p 
    JOIN CustomerOrders c
    ON p.PhoneID = c.CustomerID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM