-1

My database:

DROP TABLE IF EXISTS `login_tokens`;

CREATE TABLE `login_tokens` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `token` char(64) NOT NULL DEFAULT '',
  `user_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `token` (`token`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `login_tokens_ibfk_1` 
    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



# Dump of table users
# ------------------------------------------------------------

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `password` varchar(60) DEFAULT NULL,
  `email` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Error:

MySQL said: Documentation

1005 - Can't create table socialnetwork.login_tokens (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)

Community
  • 1
  • 1
Azazel
  • 167
  • 3
  • 12

1 Answers1

2

You need to create the table users before creating the table login_tokens.

At the time you are creating login_tokens, users does not yet exist, so there's no way of creating the "foreign key" relationship.

The Impaler
  • 45,731
  • 9
  • 39
  • 76