我正在尝试使用外键创建一些表,但是我无法通过错误150.它还说错误1005无法创建表别名。
这是我的剧本:
DROP TABLE IF EXISTS `Aliases`;
CREATE TABLE `Aliases` (
`aliasnum` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`usernum` bigint(20) unsigned NOT NULL DEFAULT '0',
`address` varchar(255) NOT NULL DEFAULT '',
`display` varchar(255) NOT NULL DEFAULT '',
`selected` tinyint(1) NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
PRIMARY KEY (`aliasnum`),
UNIQUE KEY `UNIQ_DISPLAY` (`usernum`,`address`,`display`),
KEY `IX_USERNUM` (`usernum`),
KEY `IX_USERNUM_ADDRESS` (`usernum`,`address`),
CONSTRAINT `Aliases_fk_1` FOREIGN KEY (`usernum`, `address`) REFERENCES `Mailboxes` (`usernum`, `address`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 MAX_ROWS=4294967295 AVG_ROW_LENGTH=100 COMMENT='Store mailbox display aliases and default status information.';
DROP TABLE IF EXISTS `Mailboxes`;
CREATE TABLE `Mailboxes` (
`address` varchar(255) NOT NULL DEFAULT '',
`usernum` bigint(20) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`address`),
KEY `IX_USERNUM` (`usernum`),
KEY `IX_USERNUM_ADDRESS` (`usernum`,`address`),
CONSTRAINT `Mailboxes_ibfk_1` FOREIGN KEY (`usernum`) REFERENCES `Users` (`usernum`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 MAX_ROWS=4294967295 AVG_ROW_LENGTH=100 COMMENT='All mailboxes for which we accept e-mail.';
错误表明第29行是:
`selected` tinyint(1) NOT NULL DEFAULT '0',
所有表格都是InnoDB。我真的被困住了,不确定它是什么?
答案 0 :(得分:0)
删除
CONSTRAINT `Aliases_fk_1` FOREIGN KEY (`usernum`, `address`) REFERENCES `Mailboxes` (`usernum`, `address`) ON DELETE CASCADE ON UPDATE CASCADE
和
CONSTRAINT `Mailboxes_ibfk_1` FOREIGN KEY (`usernum`) REFERENCES `Users` (`usernum`) ON DELETE CASCADE ON UPDATE CASCADE
create table
命令中的。
创建表格后添加FOREIGN KEY
ALTER TABLE `Aliases`
ADD CONSTRAINT `Aliases_fk_1`
FOREIGN KEY (`usernum`, `address`)
REFERENCES `Mailboxes` (`usernum`, `address`)
ON DELETE CASCADE
ON UPDATE CASCADE;
和
ALTER TABLE `Mailboxes`
ADD CONSTRAINT `Mailboxes_ibfk_1`
FOREIGN KEY (`usernum`)
REFERENCES `Users` (`usernum`)
ON DELETE CASCADE
ON UPDATE CASCADE;
答案 1 :(得分:0)
您的第一个表有一个约束,它引用第二个表。所以改变创作顺序。
当然,你的第二个表有一个约束,它引用了你在问题中没有提到的其他一些表Users
。因此,您必须先创建Users
,然后Mailboxes
,然后Aliases
。
或者,您可以从表定义中删除CONSTRAINT
子句,然后在表格全部可用之后创建约束,如下所示。
CREATE TABLE Users
CREATE TABLE Aliases ...
CREATE TABLE Mailboxes ...
ALTER TABLE Aliases ADD
CONSTRAINT `Aliases_fk_1` FOREIGN KEY (`usernum`, `address`) REFERENCES `Mailboxes` (`usernum`, `address`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE Mailboxes ADD
CONSTRAINT `Mailboxes_ibfk_1` FOREIGN KEY (`usernum`) REFERENCES `Users` (`usernum`) ON DELETE CASCADE ON UPDATE CASCADE;
(我认为第29行不相关。)