简体   繁体   English

将varchar列更改为另一个表SQL的外键

[英]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. 我试图将列的varchar值更改为来自另一个表的id外键值,但我似乎无法进行转换,总是抛出错误。

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... RoleName表...

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. 现在,我需要做的是让User表中的RoleName列指向RoleName表中的键。 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. 您将id放在User表中。 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;

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

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