SQL 外键格式不正确

发布于 2025-01-16 06:47:27 字数 656 浏览 3 评论 0原文

亲爱的 Stackoverflow 用户,您好,

我正在开发一个数据库以添加到我的项目中。 但我很难弄清楚如何使用 PHPmyadmin 在 MySQL 中正确建立关系。

我写了以下内容:

CREATE TABLE Orders ( 
    OrderID int(255) NOT NULL, 
    Price decimal(65,2), 
    Order_date DATE,
    UserID Int(255) NOT NULL,
    PRIMARY KEY (OrderID), 
    FOREIGN KEY (UserID) REFERENCES Users(UserID) 
); 
CREATE TABLE Users(
    UserID Varchar(255) NOT NULL,
    Password Varchar(12) NOT NULL,
    PRIMARY KEY(UserID)    
);

但我不断收到错误消息,告诉我我错误地形成了外键。 我错过了什么吗? PHPmyadmin 是否使用不同的方式来制定查询?

我看到消息来源告诉我使用索引或稍后使用表修饰符和索引来分配主键和外键,但这似乎是不必要的额外步骤,除非它确实是唯一的方法。我的知识还很有限。

错误消息:(errno:150“外键约束格式不正确”)

Hello dear Stackoverflow users,

I'm working on a database to add to my project.
But I'm having struggles figuring out properly making relations in MySQL using PHPmyadmin.

I have written the following:

CREATE TABLE Orders ( 
    OrderID int(255) NOT NULL, 
    Price decimal(65,2), 
    Order_date DATE,
    UserID Int(255) NOT NULL,
    PRIMARY KEY (OrderID), 
    FOREIGN KEY (UserID) REFERENCES Users(UserID) 
); 
CREATE TABLE Users(
    UserID Varchar(255) NOT NULL,
    Password Varchar(12) NOT NULL,
    PRIMARY KEY(UserID)    
);

But I keep getting an error telling me that I incorrectly formed the foreign key.
Am I missing something? does PHPmyadmin use a different way of formulating queries?

I have seen sources telling me to use index or later on using table modifiers and indexes to assign primary and foreign keys, but that seemed rather like unnecessary extra steps, unless it's really the only way to do it. My knowledge is yet still limited.

Error message: (errno: 150 "Foreign key constraint is incorrectly formed")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷夜 2025-01-23 06:47:27
  1. 表的创建顺序至关重要 - 您不能引用未创建的表。因此,首先创建用户,然后创建订单
  2. 您的引用列数据类型不兼容 - Users.UserID 定义为 Varchar(255),而 Orders.User_id 定义为 Int (255)。您必须在两个表中设置相同的数据类型。对于 idINT 数据类型似乎是最合理的。

附言。 Int(255) 不安全,INTEGER 数据类型无法存储 255 位数字。并且无论如何指定的长度都将被忽略。此外,它已被弃用,因此请完全删除它。

  1. The tables creation order is critical - you cannot refer to the table which is not created. So create Users firstly then Orders.
  2. Your referencing columns datatypes are not compatible - Users.UserID is defined as Varchar(255) whereas Orders.User_id is defined as Int(255). You must set the same datatype in both tables. For id column INT datatype seems to be the most reasonable.

PS. Int(255) is not safe, INTEGER datatype cannot store 255 digits. And the length specifying will be ignored anycase. Moreover, it is deprecated, so remove it at all.

北笙凉宸 2025-01-23 06:47:27

也许你可以尝试改变创建表的顺序?尝试创建第一个用户,然后创建订单

Maybe can you try change the order of create tables? Try create first User and then Orders

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文