简体   繁体   English

MySQL:在将表值设置为默认值之后,如何更新外键字段并创建关系?

[英]MySQL: How to update foreign key field, and create a relationship, after table values have been set with default values?

I have a teamnews Table: 我有一个teamnews表: 在此处输入图片说明

And another table called team: 另一个表称为team: 在此处输入图片说明

The values in teamnews table are predetermined before a user signs into the site. 在用户登录站点之前,teamnews表中的值是预先确定的。 Lets say when a user( teamName ) signs in I want to update the teamID row where NewsID = 1 And create a relationship so that if I eventually delete the user( teamName ) the teamID value in the teamNews table is reset to zero. 可以说,当一个用户( teamNameteamName ,我想更新NewsID = 1的teamID行并创建一个关系,以便如果我最终删除该用户( teamName ), teamID teamNews表中的teamID值重置为零。

Is this possible? 这可能吗? Please bare in mind I am using phpMyAdmin, so I am not entirely familiar with advanced SQL terms. 请记住我正在使用phpMyAdmin,所以我对高级SQL术语并不完全熟悉。

When I try to do this I get and error: 当我尝试执行此操作时,出现错误: 在此处输入图片说明

Here's the error: 这是错误:

在此处输入图片说明

You need to specify a FOREIGN KEY . 您需要指定一个FOREIGN KEY You can add it in by running this command: 您可以通过运行以下命令将其添加:

ALTER TABLE teamnews
ADD CONSTRAINT fk_teamID
  FOREIGN KEY (TeamID)
  REFERENCES team (teamID)
  ON DELETE SET NULL;

This sets up a formal relationship between the tables using the foreign key. 这将使用外键在表之间建立正式关系。 The ON DELETE SET NULL is the part that is important to you. ON DELETE SET NULL是对您很重要的部分。 This says that whenever any item in the referenced table ( team in this instance) is deleted, then all rows in this table that had that team id should set that field to null — exactly what you're looking for. 这就是说,只要删除引用表中的任何项目(在本例中为team ),那么该表中所有具有该team id的行都应将该字段设置为null,这正是您要查找的内容。

Be aware that this will only work if you are using the InnoDB database engine (not the MyISAM engine). 请注意,这仅在使用InnoDB数据库引擎(而不是MyISAM引擎)时才有效。 You can probably change that through phpmyadmin somewhere (I'm not familiar with phpmyadmin so I can't help you on the details). 您可能可以通过某个地方的phpmyadmin进行更改(我对phpmyadmin并不熟悉,所以我无法为您提供详细信息)。

Also be aware that for this to work, MySQL must actually be able to "SET NULL" -- the field containing the foreign key with this constraint can't be set to "NOT NULL" or it will fail with an error saying to "check data type". 另请注意,要使此方法起作用,MySQL实际上必须能够“ SET NULL”-包含具有此约束的外键的字段不能设置为“ NOT NULL”,否则它将失败并显示错误消息“检查数据类型”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM