Is it possible to create a table with multiple foreign key restraints to the same column of another table?
Example:
CREATE TABLE users (
username TEXT NOT NULL UNIQUE,
password VARCHAR(128),
userID INTEGER PRIMARY KEY AUTOINCREMENT
);
CREATE TABLE friends (
friend1 INTEGER REFERENCES users(userID),
friend1 INTEGER REFERENCES users(userID),
PRIMARY KEY(friend1, friend2)
);
Is it possible to do something like this (and is there a way to enforce friend1 != friend2
?), or do I need a different pattern entirely?
Yes, but they need to have different names:
CREATE TABLE friends (
friend1 INTEGER REFERENCES users(userID),
friend2 INTEGER REFERENCES users(userID),
PRIMARY KEY(friend1, friend2)
);
Here is a db<>fiddle.
You can define the foreign keys and the CHECK constraint
that ensures that the 2 columns are different, like this:
CREATE TABLE friends (
friend1 INTEGER NOT NULL,
friend2 INTEGER NOT NULL CHECK(friend2 <> friend1),
PRIMARY KEY(friend1, friend2),
FOREIGN KEY (friend1) REFERENCES users(userID),
FOREIGN KEY (friend2) REFERENCES users(userID)
);
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.