如何解决MySQL外键约束格式不正确的问题?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (292)
# Sql to create userdetails table:
    CREATE TABLE `userdetails` (
     `user_details_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
     `user_group_id` int(1) unsigned NOT NULL,
     `name` varchar(50) NOT NULL,
     `email_id` varchar(50) NOT NULL,
     `password` varchar(50) NOT NULL,
     `mobile_no` varchar(10) NOT NULL,
     `company_id` int(3) unsigned NOT NULL,
     `date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
     `date_updated` datetime NOT NULL,
     `created_by` int(3) unsigned NOT NULL,
     `status` enum('0','1') NOT NULL DEFAULT '0',
     PRIMARY KEY (`user_details_id`),
     UNIQUE KEY `email_id` (`email_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    # Sql to create qrcode table:
    CREATE TABLE `qrcode` (
     `qrcode_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
     `user_details_id` int(3) unsigned NOT NULL,
     `qrcode_url` varchar(50) NOT NULL,
     `allowed_entries` int(1) unsigned NOT NULL,
     `used_entries` int(1) unsigned NOT NULL,
     `expiry_date` datetime NOT NULL,
     `status` enum('0','1') NOT NULL,
     PRIMARY KEY (`qrcode_id`),
     UNIQUE KEY `user_details_id` (`user_details_id`),
     FOREIGN KEY (`user_details_id`) REFERENCES `userdetails` (`user_details_id `)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

编译时出现以下报错:

#1005 - Can't create table `esecurity`.`qrcode` (errno: 150 "Foreign key constraint is incorrectly formed")

该如何解决呢?

提问于
用户回答回答于

你在外键声明中输入了一个错误,这样修改:

FOREIGN KEY (`user_details_id`) REFERENCES `userdetails` (`user_details_id `)
Error: Can't create table 'qrcode1' (errno: 150)
SQLState:  HY000
ErrorCode: 1005

外键指向了一个不存在的列:

FOREIGN KEY (`user_details_id`) REFERENCES `userdetails` (`user_details_id`)

扫码关注云+社区

领取腾讯云代金券