MySQL:“创建表时出错:无法添加外键约束”

时间:2014-11-16 05:15:05

标签: mysql

我有两张桌子,我想引用一个id。代码如下所示。我得到:“创建表时出错:无法添加外键约束”。我认为那是因为自动增量。有人可以帮忙吗?干杯

$polls = "CREATE TABLE IF NOT EXISTS `polls` ( 
    `id_poll` INT(10) AUTO_INCREMENT, 
    `descricao` VARCHAR(255), 
    `password` VARCHAR(255), 
    `privacidade` INT(1),   
    primary key (id_poll) 
    )";

if ($conn->query($polls) === TRUE) {
    echo "Table polls: CHECK!";
} else {
    echo "Error creating table: " . $conn->error;
}


$options = "CREATE TABLE IF NOT EXISTS `opcoes` ( 
    `id_opcao` INT(10) AUTO_INCREMENT, 
    `id_poll` INT(10),
    `descricao` VARCHAR(255), 
    primary key (id_opcao),
    FOREIGN KEY (id_poll) REFERENCES polls(id_poll)
    )";

if ($conn->query($opcoes) === TRUE) {
    echo "Table opcoes: CHECK!";
} else {
    echo "Error creating table: " . $conn->error;
}

1 个答案:

答案 0 :(得分:0)

两个表上的id_poll必须为NOT NULL。这是代码。

$polls = "CREATE TABLE IF NOT EXISTS `polls` ( 
    `id_poll` INT(10) NOT NULL AUTO_INCREMENT, 
    `descricao` VARCHAR(255), 
    `password` VARCHAR(255), 
    `privacidade` INT(1),   
    primary key (id_poll) 
    )";

if ($conn->query($polls) === TRUE) {
    echo "Table polls: CHECK!";
} else {
    echo "Error creating table: " . $conn->error;
}


$options = "CREATE TABLE IF NOT EXISTS `opcoes` ( 
    `id_opcao` INT(10) AUTO_INCREMENT, 
    `id_polls` INT(10) NOT NULL,
    `descricao` VARCHAR(255), 
    primary key (id_opcao),
    FOREIGN KEY (id_polls) REFERENCES polls(id_poll)
    )";

if ($conn->query($options) === TRUE) {
    echo "Table opcoes: CHECK!";
} else {
    echo "Error creating table: " . $conn->error;
}