创建表时sql外键出现问题

brgchamk  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(360)

我用一个函数外键将两个表链接在一起。
我犯了一个错误:“errno:150”外键约束的格式不正确。
我找不出问题出在哪里。请,我将感谢任何建议。
谢谢你的帮助。
这是我用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 ();

?>
dddzy1tm

dddzy1tm1#

您的字段具有不同的数据类型。
引用的列是类型为id int(6)的无符号自动增量主键的us\u taddress中的id。
引用列是来自类型为int(6)的us\u tuser的address\u id。
必须将表us\u taddress中id列的类型更改为signed,或将表us\u tuser中字段address\u id的数据类型更改为unsigned。

相关问题