2016-04-24 76 views
-2

我正在尝试创建几个表格,但无法使钥匙正常工作。看不出为什么它不起作用

Create table FAQ (
id int(10) PRIMARY KEY AUTO_INCREMENT, 
question text, 
answer text 
); 
Create table templates (
id int(10) AUTO_INCREMENT, 
name varchar(80), 
value varchar(30), 
sql_db text, 
sql_table text, 
Primary Key(id,name,value) 
); 
Create table clientes(
id int(10) AUTO_INCREMENT, 
nome varchar(80), 
email varchar(30), 
website varchar(80), 
template_name varchar(80), 
template_value varchar(30), 
modo varchar(10), 
data datetime, 
Primary Key (id), 
FOREIGN KEY (template_name) REFERENCES templates(name), 
FOREIGN KEY (template_value) REFERENCES templates(value) 
); 

我只是想在这两张表之间做简单的关系。

+0

在ID,名称和值上构建PK有点奇怪 – Strawberry

回答

1

您的问题的直接答案是,一个外键需要引用所有列的唯一键。这也需要在两列的唯一索引,所以它应该是这样的:

Create table FAQ (
    id int(10) PRIMARY KEY AUTO_INCREMENT, 
    question text, 
    answer text 
); 

Create table templates (
    id int(10) AUTO_INCREMENT, 
    name varchar(80), 
    value varchar(30), 
    sql_db text, 
    sql_table text, 
    Primary Key(id), 
    Unique (name, value) 
); 

Create table clientes (
    id int(10) AUTO_INCREMENT, 
    nome varchar(80), 
    email varchar(30), 
    website varchar(80), 
    template_name varchar(80), 
    template_value varchar(30), 
    modo varchar(10), 
    data datetime, 
    Primary Key (id), 
    FOREIGN KEY (template_name, template_value) REFERENCES templates(name, value) 
); 

然而,最好是使用主键(自动增加ID)。然后你使用join查找名称和值:

Create table clientes (
    id int(10) AUTO_INCREMENT, 
    nome varchar(80), 
    email varchar(30), 
    website varchar(80), 
    template_id int, 
    modo varchar(10), 
    data datetime, 
    Primary Key (id), 
    FOREIGN KEY (template_id) REFERENCES templates(id) 
); 
相关问题