我该如何解决表

时间:2019-12-03 11:18:23

标签: php mysql

我试图在php中创建一个表,但是每次我运行它时,它总是说表中不存在键列'survey_type_id'

survey_type表

    $sql = "CREATE TABLE survey_type (
    survey_type_id INT NOT NULL AUTO_INCREMENT, 
    type VARCHAR(40),
    PRIMARY KEY(survey_type_id))";

调查表

$sql = "CREATE TABLE survey(
id INT NOT NULL AUTO_INCREMENT, 
username VARCHAR(64), 
title VARCHAR(150), 
instructions VARCHAR(250),
PRIMARY KEY(id), 
FOREIGN KEY(username) REFERENCES users(username), 
FOREIGN KEY(survey_type_id) REFERENCES survey_type(survey_type_id))";

2 个答案:

答案 0 :(得分:0)

看看这句话,这个问题应该很明显:

CREATE TABLE survey
(
    id INT NOT NULL AUTO_INCREMENT, 
    username VARCHAR(64), 
    title VARCHAR(150), 
    instructions VARCHAR(250),
    PRIMARY KEY(id), 
    FOREIGN KEY(username) REFERENCES users(username), 
    FOREIGN KEY(survey_type_id) REFERENCES survey_type(survey_type_id)
)

该语句正在survey.survey_type_idsurvey_type.survey_type_id两列之间创建外键。

但是,survey_type_id表上没有名为survey的列。

用于创建survey表的语句应包含survey_type_id列的定义:

    ...
    instructions VARCHAR(250),
    survey_type_id INT,
    PRIMARY KEY(id), 
    ...

答案 1 :(得分:0)

您错过了参考表中的survey_type_id列,这就是您出错的原因。

CREATE TABLE survey(
id INT NOT NULL AUTO_INCREMENT, 
username VARCHAR(64), 
title VARCHAR(150), 
instructions VARCHAR(250),
survey_type_id INT(11),  //Missout by you please add this
PRIMARY KEY(id), 
FOREIGN KEY(username) REFERENCES users(username), 
FOREIGN KEY(survey_type_id) REFERENCES survey_type(survey_type_id))

添加列http://www.sqlfiddle.com/#!9/680d26

之后