[英]Issue with SQL FOREIGN KEY on CREATE TABLE
I used to a function FOREIGN KEY for link two tables together.我曾经使用 function FOREIGN KEY 将两个表链接在一起。
I'm straggling with that error: "errno: 150 "Foreign key constraint is incorrectly formed".我对这个错误感到困惑: “errno:150”外键约束的格式不正确”。
I could not find out where is problem.我找不到问题出在哪里。 Please, I will thankful for any suggestions.
请,我会感谢任何建议。
Thank, you for help.谢谢你的帮助。
This is my script written in PHP(see below).这是我用 PHP 编写的脚本(见下文)。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "myDB";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connection_error);
}
echo "Connected successfully";
$sql = "CREATE DATABASE IF NOT EXISTS myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$sql = "CREATE TABLE IF NOT EXISTS us_tAddress (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
country VARCHAR(100),
city VARCHAR(100),
zip VARCHAR(100),
street VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ";
if ($conn->query($sql) === TRUE) {
echo "Table us_tAddress created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$sql = "CREATE TABLE IF NOT EXISTS us_tUser (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
address_id INT (6),
first_name VARCHAR(100),
last_name VARCHAR(100),
position VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (address_id) REFERENCES us_tAddress (id)
) ";
if ($conn->query($sql) === TRUE) {
echo "Table us_tUser created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close ();
?>
Your fields have different datatype.您的字段具有不同的数据类型。
Referenced column is id from us_tAddress with type id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY.引用的列是来自us_tAddress的 id,类型 id 为 INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY。
Referencing column is address_id from us_tUser with type INT (6).引用列是来自us_tUser的 address_id,类型为 INT (6)。
You have to change type of id column in table us_tAddress to SIGNED or change datatype of field address_id in table us_tUser to UNSIGNED.您必须将表 us_tAddress 中 id 列的类型更改为 SIGNED 或将表 us_tUser 中的字段 address_id 的数据类型更改为 UNSIGNED。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.