错误消息:使用CONSTRAINT创建表时出现121“写入或更新时重复密钥”

时间:2019-01-19 21:34:57

标签: mysql mariadb

我使用以下代码创建了一个表

CREATE TABLE `Notes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `title` text,
  `content` text,
  `public` tinyint(1) DEFAULT NULL,
  `userid` int(11) NOT NULL,
  `beerid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `userid` (`userid`),
  KEY `beerid` (`beerid`),
  CONSTRAINT `Notes_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `Users` (`id`),
  CONSTRAINT `Notes_ibfk_2` FOREIGN KEY (`beerid`) REFERENCES `Beers` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
  

第87行的错误1005(HY000):无法创建表beersafeNotes   (错误号:121“写入或更新时出现重复密钥”)

mysqladmin  Ver 9.1 Distrib 10.0.36-MariaDB, for debian-linux-gnu on x86_64
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Server version      10.0.36-MariaDB-0ubuntu0.16.04.1
Protocol version    10
Connection      Localhost via UNIX socket
UNIX socket     /var/run/mysqld/mysqld.sock
Uptime:         17 hours 14 min 49 sec

(来自评论)

CREATE TABLE Beers (
    id int(11) NOT NULL AUTO_INCREMENT, 
    name varchar(50) DEFAULT NULL, 
    image text, 
    alcohol float DEFAULT NULL, 
    color varchar(50) DEFAULT NULL, 
    category text, 
    description text, 
    PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;

CREATE TABLE Users (
    id int(11) NOT NULL AUTO_INCREMENT, 
    email text, 
    password text, 
    name text, 
    PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; 

SELECT  *
    FROM  INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE  CONSTRAINT_NAME IN ('Notes_ibfk_1', 'Notes_ibfk_2');

| def | BeerSafe | Notes_ibfk_1 | BeerSafe | Notes | FOREIGN KEY |
| def | BeerSafe | Notes_ibfk_2 | BeerSafe | Notes | FOREIGN KEY |

1 个答案:

答案 0 :(得分:0)

我使用以下代码创建表“ Notes”

创建表Notes(   id int(11)NOT NULL AUTO_INCREMENT,   created时间戳记非空默认CURRENT_TIMESTAMP开启UPDATE CURRENT_TIMESTAMP,   title文字,   content文字,   public tinyint(1)缺省为NULL,   userid int(11)NOT NULL,   beerid int(11)NOT NULL,   主键(id),   键useriduserid),   键beeridbeerid) )ENGINE = InnoDB AUTO_INCREMENT = 5 DEFAULT CHARSET = latin1;

已删除 ” 约束Notes_ibfk_1外键(userid)参考Usersid), 约束Notes_ibfk_2外键(beerid)参考Beersid) “