简体   繁体   中英

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: 在此处输入图片说明

And another table called team: 在此处输入图片说明

The values in teamnews table are predetermined before a user signs into the site. 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.

Is this possible? Please bare in mind I am using phpMyAdmin, so I am not entirely familiar with advanced SQL terms.

When I try to do this I get and error: 在此处输入图片说明

Here's the error:

在此处输入图片说明

You need to specify a 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. 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.

Be aware that this will only work if you are using the InnoDB database engine (not the MyISAM engine). You can probably change that through phpmyadmin somewhere (I'm not familiar with phpmyadmin so I can't help you on the details).

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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