在SQL中与外键的关系?

时间:2021-07-03 11:30:47

I am translating a recursive relationship in a schema to sql and i am trying to reference two columns in a table to one column in another table the Schema is as following :

我正在将模式中的递归关系转换为sql,我试图将表中的两列引用到另一个表中的一列,Schema如下:

Table: Request
(
   mem_id1,
   mem id2,
   approved
)  

desired foreign keys:

想要的外键:

request.mem_id1 will reference member.mem_id  
request.mem_id2 will reference member.mem_id 

I have tried the following:

我尝试过以下方法:

CREATE TABLE members (
mem_id INTEGER,
f_name VARCHAR(10),
l_name VARCHAR(10),
address VARCHAR(40),
name VARCHAR(20),
domain VARCHAR(15),
PRIMARY KEY(mem_id)
)

CREATE TABLE member_phone (
mem_id INTEGER,
phone_no INTEGER,
PRIMARY KEY (mem_id,phone_no),
FOREIGN KEY (mem_id) REFERENCES members (mem_id)
)

CREATE TABLE request (
mem_id1 INTEGER,
mem_id2 INTEGER,
approved BIT(1),
PRIMARY KEY (mem_id1,mem_id2),
FOREIGN KEY (mem_id1,mem_id2) REFERENCES members (mem_id)
)

1 个解决方案

#1


2  

I believe you want two separate foreign keys:

我相信你想要两个独立的外键:

CREATE TABLE request (
mem_id1 INTEGER,
mem_id2 INTEGER,
approved BIT(1),
PRIMARY KEY (mem_id1, mem_id2),
FOREIGN KEY (mem_id1) REFERENCES members (mem_id),
FOREIGN KEY (mem_id2) REFERENCES members (mem_id)
)

#1


2  

I believe you want two separate foreign keys:

我相信你想要两个独立的外键:

CREATE TABLE request (
mem_id1 INTEGER,
mem_id2 INTEGER,
approved BIT(1),
PRIMARY KEY (mem_id1, mem_id2),
FOREIGN KEY (mem_id1) REFERENCES members (mem_id),
FOREIGN KEY (mem_id2) REFERENCES members (mem_id)
)