简体   繁体   中英

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. 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?

Thank you, Andrew

To do this you would want a CHECK constraint. However MySQL hasn't implemented CHECK constraints yet, so you can use a trigger instead.

Related

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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