在SQL中与外键的关系?

时间:2011-11-12 17:58:27

标签: mysql sql database schema

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

Table: Request
(
   mem_id1,
   mem id2,
   approved
)  

所需的外键:

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

我尝试了以下内容:

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 个答案:

答案 0 :(得分:2)

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

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)
)