简体   繁体   English

如何限制MySQL中的自引用表,这样一行不能引用自身?

[英]How to limit a self-referencing table in MySQL so a row can't reference itself?

Here is a very basic table to illustrate my question. 这是一个非常基本的表来说明我的问题。

CREATE TABLE Customer (
CustID         INT,
CustLastName   VARCHAR (20),
ReferralID     INT,
ADD CONSTRAINT PRIMARY KEY (CustID),
ADD CONSTRAINT FOREIGN KEY (ReferralID) REFERENCES Customer(CustID)
);

My current code ensures that any only former customers who have CustID's can be in the ReferralID column (ie they told the customer about the store.) However, the problem is nothing is stopping CustID from equaling ReferralID in the same row, which is obviously impossible. 我当前的代码确保任何只有CustID的前客户都可以在ReferralID列中(即他们告诉客户有关商店的信息。)然而,问题是没有什么能阻止CustID在同一行中等于ReferralID,这显然是不可能的。 A customer cannot tell themself about the store. 顾客无法告诉自己有关商店的信息。

Basically, how do I stop CustID and ReferralID from having the same value in the same row? 基本上,如何阻止CustID和ReferralID在同一行中具有相同的值?

Thank you, Andrew 谢谢你,安德鲁

To do this you would want a CHECK constraint. 为此,您需要CHECK约束。 However MySQL hasn't implemented CHECK constraints yet, so you can use a trigger instead. 但是,MySQL尚未实现CHECK约束,因此您可以使用触发器。

Related 有关

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

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