简体   繁体   English

SQL在同一表上的关系

[英]Relationships in SQL on the same table

I haven't ever really used foreign keys in my databases, I have always just written code that would enforce things for me, but I'm looking towards shifting some of that logic to the database and learning more about foreign keys. 我从来没有真正在数据库中使用过外键,我一直只是编写可以对我强制执行功能的代码,但我希望将某些逻辑转移到数据库中,并进一步了解外键。

I currently have a database which has the table Categories : 我目前有一个数据库,其中包含表Categories

CREATE TABLE [dbo].[Categories](
    [CategoryID] [bigint] IDENTITY(1,1) NOT NULL,
    [ParentCategoryID] [bigint] NOT NULL,
    [CategoryStatus] [bit] NOT NULL,
    [CategoryTitle] [varchar](64) NOT NULL,
    [CategorySlug] [varchar](64) NOT NULL,
    [CategoryThumbnail] [varchar](128) NULL,
    [CategoryHeaderImage] [varchar](128) NULL,
    [CategoryDescription] [text] NULL,
 CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED 
(
    [CategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UI_Categories_Slug] UNIQUE NONCLUSTERED 
(
    [CategorySlug] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

I would like to create a foreign key that relates ParentCategoryID back up to CategoryID . 我想创建一个将ParentCategoryID关联到CategoryID的外键。 When creating the FK, which would be the primary column, and which would be the foreign column in this instance? 在创建FK时,在这种情况下,哪个将为主列,哪个将为外部列?

I would think that ParentCategoryID would have to be NULL able (unless you want a top-level parent to point to itself, and that doesn't make much sense). 我认为ParentCategoryID必须具有NULL (除非您希望顶级父级指向自身,否则这没有多大意义)。

ALTER TABLE dbo.Categories
  ADD CONSTRAINT FK_SelfParent
  FOREIGN KEY (ParentCategoryID)
  REFERENCES dbo.Categories(CategoryID);

True story: at a job interview at Microsoft (several years ago), a SQL Server person told me that this wasn't possible. 真实的故事:几年前在Microsoft接受一次工作面试时,一位SQL Server人士告诉我这是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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