简体   繁体   中英

Foreign Key not adding in while doing alter table?

Here is my users.sql file :

CREATE TABLE users (
    'id' bigint(20) NOT NULL auto_increment,
    'md5_id' varchar(200) collate latin1_general_ci NOT NULL default '',
    'user_name' varchar(200) collate latin1_general_ci NOT NULL default '',
    'user_email' varchar(220) collate latin1_general_ci NOT NULL default '',
     ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci 
       AUTO_INCREMENT=55 ;

Here id is the primary key.

Now this is the second table notifications.sql:

CREATE TABLE 'notifications' (
 'notificationid' int(11) NOT NULL,
 'creation_date_time' varchar(30) NOT NULL,
 'view_date_time' varchar(30) NOT NULL,
  'user_id bigint(big) NOT NULL,
  'notification_text' varchar(255) NOT NULL,
  'is_viewed' varchar(3) NOT NULL

)

Now when i try to add id in notifications table as foreign key it gives 1215 error. I don't know where i am going wrong.

This is my alter table code:

ALTER TABLE 'notifications'
ADD FOREIGN KEY (id) REFERENCES users(id)
ON DELETE CASCADE ON UPDATE CASCADE

You have to add the engine,charste and collate information to the second table too:

CREATE TABLE 'notifications' (
 'notificationid' int(11) NOT NULL,
 'creation_date_time' varchar(30) NOT NULL,
 'view_date_time' varchar(30) NOT NULL,
  'user_id bigint(big) NOT NULL,
  'notification_text' varchar(255) NOT NULL,
  'is_viewed' varchar(3) NOT NULL

)
ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci 

Also your table notifications ha no column id . You have to add this first and Name it user_id:

ALTER TABLE 'notifications'
ADD Column user_id int(11);


ALTER TABLE 'notifications'
ADD FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE ON UPDATE CASCADE

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