简体   繁体   中英

Changing varchar column to foreign key of another table SQL

I'm trying to change a column's varchar values to it's id foreign key value from another table, and I can't seem to make the conversion, always throws an error.

User table...

CREATE TABLE User(
UserId INT NOT NULL AUTO_INCREMENT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(50),
Username VARCHAR(20) NOT NULL,
Password VARCHAR(50) NOT NULL,
RoleName VARCHAR(50) NOT NULL,
LastLogin DATETIME,

PRIMARY KEY(UserId)
);

INSERT INTO User 
 (FirstName, LastName, Email, Username, Password, RoleName)
VALUES 

...

RoleName table...

create table rolename(
                RoleId int not null auto_increment,
                RoleName varchar(50),
                primary key(RoleId)
);
insert into rolename(RoleName) select distinct RoleName from user;

Now, what I need to do is have the RoleName column in the User table point to the key in the RoleName table. I keep trying this, but always gives me an error.

update user set user.`RoleName` = rolename.`RoleId` from user inner join rolename on user.`RoleName` = rolename.`RoleName`;

I'm not sure if I'm setting up the foreign key properly with that code either...

No, you are doing this wrong. You put the id in the User table. To fix this:

alter table user add roleid int;
alter table user add constraint fk_user_roleid foreign key (roleid)  references rolename(roleid);

Then populate the values:

update user u join
       rolename r
       on r.rolename = u.rolename
    set u.roleid = r.roleid;

And get rid of the old column!

alter table user drop column rolename;

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