用外键将行插入表中

时间:2018-08-15 02:46:58

标签: sql

我在SupplierName数据库中创建了两个表(SupplierAddressaddress_book)。

SupplierName插入了一行,如下面的插入语句所示。我正在努力如何将数据插入名为SupplierAddress的表中。

请注意,SupplierID表中的SupplierName(主键)是SupplierAddress表中的外键。如果我的桌子设计不正确,请对此也有所看法。我只是试图创建一个简单的数据库来学习SQL。

CREATE TABLE SupplierName
(
    SupplierID int Primary Key identity(1,1) NOT NULL,
    CompanyName varchar(50) NOT NULL,
    EIN char(9) NOT NULL UNIQUE
)

CREATE TABLE SupplierAddress
(
    ID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
    Address varchar(50),
    City varchar(50),
    State char(2),
    ZipCode char(5),
    Phone varchar(10),
    SupplierAddressID int FOREIGN KEY REFERENCES SupplierName(SupplierID)
)

INSERT INTO SupplierName (CompanyName, EIN)
VALUES ('Clarks Electronics, Inc.', '123456789');

INSERT INTO SupplierAddress (Address, City, State, ZipCode, Phone)
VALUES ('2020 Garnet Road', 'York', 'PA', '17403', '717-123-4567')

SELECT
    SupplierName.SupplierID, SupplierAddress.SupplierAddressID 
FROM
    SupplierName
INNER JOIN 
    SupplierAddress ON SupplierAddressID=SupplierID

1 个答案:

答案 0 :(得分:1)

从电话号码中删除连字符,或在电话中创建包含更多字符的表格

查看http://www.dpriver.com/pp/sqlformat.htm,以漂亮地格式化sql

CREATE TABLE supplieraddress
  (
     id                INT PRIMARY KEY IDENTITY(1, 1) NOT NULL,
     address           VARCHAR(50),
     city              VARCHAR(50),
     state             CHAR(2),
     zipcode           CHAR(5),
     phone             VARCHAR(10),  -- make this longer
     supplieraddressid INT FOREIGN KEY REFERENCES suppliername(supplierid)
  ) 


INSERT INTO supplieraddress
            (address,
             city,
             state,
             zipcode,
             phone)
-- add  supplieraddressid  and its value so that the FK is created
VALUES     ('2020 Garnet Road',
            'York',
            'PA',
            '17403',
            '717-123-4567')  -- or  remove hyphens

SELECT suppliername.supplierid,
       supplieraddress.supplieraddressid
FROM   suppliername
       INNER JOIN supplieraddress
               ON supplieraddressid = supplierid