简体   繁体   English

SQL,同一表中的外键

[英]SQL, foreign keys in same table

Can I have a column in a table be a foreign key for another column in the table? 我可以在表中的一列作为表中另一列的外键吗? For example, if one column is OrderId and another column is RelatedOrderId , could OrderId be a "foreign key" for RelatedOrderId ? 例如,如果一列OrderId ,另一列是RelatedOrderId ,可能OrderId是一个“外键”为RelatedOrderId The idea behind such a relationship would be that it would tell whoever is looking at the table that those two columns can have overlapping values. 这种关系背后的想法是,它将告诉正在查看表的任何人这两列可以具有重叠的值。

This may be as close as you can get: 这可能与您得到的尽可能接近:

CREATE TABLE `a9` (
  `orderId` int(11) NOT NULL,
  `relatedOrderId` int(11) DEFAULT NULL,
  PRIMARY KEY (`orderId`),
  KEY `abcd3` (`relatedOrderId`),
  CONSTRAINT `abcd3` FOREIGN KEY (`relatedOrderId`) REFERENCES `a9` (`orderId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert a9(orderId,relatedOrderId) values (1,null); -- success
insert a9(orderId,relatedOrderId) values (2,3); -- Error 1452
insert a9(orderId,relatedOrderId) values (2,1); -- success

And the referential integrity is not terribly strong with a NULL in the column relatedOrderId . 并且,在relatedOrderId列中使用NULL ,引用完整性不是很强。 But at least it suggests that if not NULL then it is valid. 但至少它表明,如果不为NULL那么它是有效的。

To achieve a circular reference, one would need to do the below which seems fishy. 为了获得一份循环参考,需要做以下似乎很棘手的事情。

insert a9(orderId,relatedOrderId) values (1,null); -- success
insert a9(orderId,relatedOrderId) values (2,1); -- success
update a9 set relatedOrderId=2 where orderId=1; -- success

select * from a9;
+---------+----------------+
| orderId | relatedOrderId |
+---------+----------------+
|       2 |              1 |
|       1 |              2 |
+---------+----------------+

Forgive the datatypes chosen. 原谅所选的数据类型。 It is only an example. 这只是一个例子。

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

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