且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

外键可以引用同一表中的主键吗?

更新时间:2022-12-12 16:42:56

我认为这个问题有点令人困惑.

I think the question is a bit confusing.

如果您的意思是外键可以引用"同一张表中的主键吗?",答案是肯定的.例如,在雇员表中,雇员的行可能具有用于存储经理的雇员编号的列,其中经理也是雇员,因此表中的行将与其他雇员的行一样.

If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied. For example, in an employee table, a row for an employee may have a column for storing manager's employee number where the manager is also an employee and hence will have a row in the table like a row of any other employee.

如果您的意思是同一列表中的列(或列集)既可以是主键又可以是外键?",我认为答案是否定的;似乎毫无意义.但是,以下定义在SQL Server中成功!

If you mean "can column(or set of columns) be a primary key as well as a foreign key in the same table?", the answer, in my view, is a no; it seems meaningless. However, the following definition succeeds in SQL Server!

create table t1(c1 int not null primary key foreign key references t1(c1))

但是我认为,除非有人提出一个实际的例子,否则具有这样的约束是没有意义的.

But I think it is meaningless to have such a constraint unless somebody comes up with a practical example.

AmanS,在您的示例中,d_id在任何情况下都不能成为Employee表中的主键.一个表只能有一个主键.我希望这可以消除您的疑问. d_id仅在部门表中是/可以是主键.

AmanS, in your example d_id in no circumstance can be a primary key in Employee table. A table can have only one primary key. I hope this clears your doubt. d_id is/can be a primary key only in department table.