我在使用带有外键元素的MySQL(PDO)创建一个表时遇到困难,没有表创建的外键,但没有我收到此消息:
SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法出错;
我尝试过搜索解决方案并调整代码,但似乎不断遇到这个问题。有没有解决方法,或者我是一个沃利?
<?php
$servername = "localhost";
$username = "root";
$password = NULL;
$dbname = "testapplciants";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//sql to create the activity registered table
$sql = "CREATE TABLE Activity_Register (
Activity_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
participant_id INT(6) FOREIGN KEY (participant_id) REFERENCES participants,
entry_number INT(2),
recorded_result INT(6),
entry_date TIMESTAMP
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table Activity Recorder created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
答案 0 :(得分:2)
PRIMARY KEY
是读取PRIMARY KEY (`column_name`)
的单独定义的简写
FOREIGN KEY
没有这样的简写。
`participant_id` INT(6),
FOREIGN KEY (`participant_id`) REFERENCES `participants` (`id???`)
请注意,您忽略了引用表的列名,您也可能也有ON DELETE
和ON UPDATE
参数。