Search code examples
sql.netsql-serverforeign-keys

How can I add two different features as a foreign key to my SQL Column?


My Car Table and I want to add 2 foreign key as you see

I have a Car table in my Sql Data and every car has own BrandId that declared every Brands in "Brands" table as a foreign key. I'm just wondering what if I want to add two different BrandId together in my one Car>BrandId Column, what would I do? How can it be possible for adding two features as a foreign key in one spesific column?

Here is my Car Tables Code

CREATE TABLE [dbo].[Cars] (
[CarId]      INT           IDENTITY (1, 1) NOT NULL,
[CarName]    VARCHAR (255) NULL,
[ColorId]    INT           NULL,
[BrandId]    INT           NULL,
[ModelYear]  VARCHAR (255) NULL,
[DailyPrice] DECIMAL (18)  NULL,
[Details]    VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([CarId] ASC),
FOREIGN KEY ([ColorId]) REFERENCES [dbo].[Colors] ([ColorId]),
FOREIGN KEY ([BrandId]) REFERENCES [dbo].[Brands] ([BrandId])
);

And here te code of my Brands table;

CREATE TABLE [dbo].[Brands] (
[BrandId]   INT           IDENTITY (1, 1) NOT NULL,
[BrandName] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([BrandId] ASC)
);

Solution

  • You can simply create your table as follows :

    CREATE TABLE [dbo].[Cars] (
    [CarId]      INT           IDENTITY (1, 1) NOT NULL,
    [CarName]    VARCHAR (255) NULL,
    [ColorId]    INT           NULL,
    [BrandId1]    INT           NULL,
    [BrandId2]    INT           NULL,
    [ModelYear]  VARCHAR (255) NULL,
    [DailyPrice] DECIMAL (18)  NULL,
    [Details]    VARCHAR (255) NULL,
    PRIMARY KEY CLUSTERED ([CarId] ASC),
    FOREIGN KEY ([ColorId]) REFERENCES [dbo].[Colors] ([ColorId]),
    FOREIGN KEY ([BrandId1]) REFERENCES [dbo].[Brands] ([BrandId]),
    FOREIGN KEY ([BrandId2] REFERENCES [dbo].[Brands] ([BrandId])