“表中不存在关键列'用户名'”

时间:2013-12-03 04:32:10

标签: php mysql sql database

我正在创建三个表,当我尝试绑定主键和外键时,我收到错误消息“键列'用户名'在表中不存在”。

有人可以看看我的代码并告诉我我做错了什么吗?我试过删除数据库并重新调整表格几次,但我仍然得到相同的消息。这是我的代码,请提前感谢您的帮助!

 create database testproject
 use testproject
 create table caller_info
 (
   caller_id int(11) unsigned auto_increment primary key not null,
   first_name varchar(35) not null, 
   Last_name varchar(35) not null, 
   phone_number int(25) not null
 );  
create table caller_call_record
(
    call_record_id int(11),
    Call_Description varchar(50), 
    franchise_id int(10) not null, 
    email varchar(40) not null, 
    username varchar(25) primary key not null
);
create table caller_escalation
(
    call_escalation_id int(11) unsigned auto_increment not null, 
    Second_Level varchar(5) not null, 
    caller_id int(11) not null, 
    PRIMARY KEY(call_escalation_id),
    FOREIGN KEY(caller_id) 
    REFERENCES caller_info(caller_id),
    FOREIGN KEY(username) REFERENCES caller_call_record(username)
);

3 个答案:

答案 0 :(得分:0)

试试这个:

create table caller_call_record
(
            call_record_id int(11),
            Call_Description varchar(50), 
            franchise_id int(10) not null, 
            email varchar(40) not null, 
            username varchar(25) not null,
            PRIMARY KEY (username)    
    );



create table caller_escalation
(
    call_escalation_id int(11) unsigned auto_increment not null, 
    Second_Level varchar(5) not null, 
    caller_id int(11) not null,
    username varchar(25) not null, 
    PRIMARY KEY(call_escalation_id,username),
    FOREIGN KEY(caller_id) 
    REFERENCES caller_info(caller_id),
    FOREIGN KEY(username) REFERENCES caller_call_record
);

答案 1 :(得分:0)

表caller_escalation还需要一个列用户名,而不是

create table caller_escalation
(
    call_escalation_id int(11) unsigned auto_increment not null, 
    Second_Level varchar(5) not null, 
    caller_id int(11) unsigned not null, ;; <--- added unsigned type here
    PRIMARY KEY(call_escalation_id),
    username varchar(25) not null,       ;; <--- added field here
    FOREIGN KEY(caller_id) 
    REFERENCES caller_info(caller_id),
    FOREIGN KEY (username) REFERENCES caller_call_record (username)
);

同时确保两个表中的列数据类型相同。你在caller_info中有“caller_id int(11)unsigned”,在caller_escalation中有“caller_id int(11)”。我在上面添加了无符号说明符,使其工作。

答案 2 :(得分:0)

如上所述,您的表caller_escalation需要一个名为username的列才能创建外键。

听起来好像一旦你添加了它,你现在从MySQL收到Cannot add foreign key constraint错误。这种错误让人想到的第一件事就是你正在为你的表使用错误的引擎。您最有可能使用不支持外键引用的MyISAM - 为了使用这些引用,您需要将所有表上的引擎更改为InnoDB