SQL:创建多个外键和约束

时间:2016-11-08 14:49:44

标签: mysql sql database

我正在尝试创建一个表,但它有5个外键并且无法将其排序。没有使用约束并继续得到错误“外键约束形成错误”这是表:

CREATE TABLE wines(
    wine_ID CHAR(7),
    color_code CHAR(1),
    country_code CHAR(6),
    grape_variety_code CHAR(9),
    region_code CHAR(4),
    vineyard_code CHAR(8),
    wine_name VARCHAR(100),
    price VARCHAR(5),
    PRIMARY KEY (wine_ID),
    CONSTRAINT FK_reColors FOREIGN KEY (color_code) REFERENCES refColors(color_code),
    CONSTRAINT FK_refCountry FOREIGN KEY (country_code) REFERENCES refCountry(country_code),
    CONSTRAINT FK_refGrapeVariety FOREIGN KEY (grape_variety_code) REFERENCES refGrapeVariety(grape_variety_code),
    CONSTRAINT FK_refRegions FOREIGN KEY (region_code) REFERENCES refRegions(region_code),
    CONSTRAINT FK_refVineyard FOREIGN KEY (vineyard_code) REFERENCES refVineyard(vineyard_code)
);

1 个答案:

答案 0 :(得分:0)

CREATE TABLE wines(
 wine_ID CHAR(7) IDENTITY(1,1) NOT NULL,,
 color_code CHAR(1) NULL,
 country_code CHAR(6) NULL,
 grape_variety_code CHAR(9) NULL,
 region_code CHAR(4) NULL,
 vineyard_code CHAR(8) NULL,
 wine_name VARCHAR(100) NULL,
 price VARCHAR(5)NULL, 
 CONSTRAINT [PK_Contact] PRIMARY KEY CLUSTERED 
    (
        [wine_ID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO


ALTER TABLE [dbo].[refColors]  WITH CHECK ADD  CONSTRAINT [FK_reColors] FOREIGN KEY([color_code])
REFERENCES [dbo].[refColors] ([color_code])
GO

.... 添加其他类似的FK