SQL将ID添加到外键id

时间:2016-12-16 01:12:25

标签: sql sql-server foreign-keys

Create Table ProductCategory(ProductCategory_ID int IDENTITY Primary Key,   
                             ProductCategory varchar(50))

Insert Into Product(ProductCategory)
Select pc.ProductCategory
From ProductCategory pc left join Product p
on p.Category = pc.ProductCategory
Group By p.Category
Order By p.Category

Alter Table Product
Add Constraint FK_ProductCategoryID
Foreign Key (ProductCategoryID)
References ProductCategory(ProductCategory_ID)

据说当我这样做时:

    Select p.ProductCategoryID
    From Product p

它应该从“ProductCategory”表中提供类别的ID。但它只是给我NULL 当我这样做时:

Select *
From ProductCategory

我获得了所有正确的ID和类别。关于我哪里出错的任何想法?

1 个答案:

答案 0 :(得分:0)

运行此功能,看看你得到了什么

Select pc.ProductCategory
From ProductCategory pc 
left join Product p
       on p.Category = pc.ProductCategory
Group By p.Category
Order By p.Category