navicat mysql中,引用属性组作为外键,其中一个无法引用
引用另一个表中的属性组(主码)作为外键,一个正常,另一个无法添加外键,这是为什么?
这个问题纠结了两天了……为什么为什么为什么?????????
SQL code
CREATE TABLE `match` (
`matchNO` varchar(50) NOT NULL,
`place` varchar(50) NOT NULL,
`matchGoals` int(11) DEFAULT NULL,
PRIMARY KEY (`matchNO`,`place`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
SQL code
CREATE TABLE `join` (
`teamNameJ` varchar(50) NOT NULL,
`matchNO` varchar(50) NOT NULL,
`place` varchar(50) NOT NULL,
`result` varchar(50) DEFAULT NULL,
PRIMARY KEY (`teamNameJ`,`matchNO`,`place`),
KEY `matchNO` (`matchNO`),
KEY `place` (`place`),
CONSTRAINT `matchNO` FOREIGN KEY (`matchNO`) REFERENCES `match` (`matchNO`), //正常
CONSTRAINT `teamNameJ` FOREIGN KEY (`teamNameJ`) REFERENCES `team` (`teamName`),//正常
CONSTRAINT `place` FOREIGN KEY (`place`) REFERENCES `match` (`place`) //place外键无法插入
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
------解决方案--------------------可能你对主键的概念理解不够深入,子表的外键必须依赖的是主表的主键的全部。
这样写就对了:
CREATE TABLE `join` (
`teamNameJ` varchar(50) NOT NULL,
`matchNO` varchar(50) NOT NULL,
`place` varchar(50) NOT NULL,
`result` varchar(50) DEFAULT NULL,
PRIMARY KEY (`teamNameJ`,`matchNO`,`place`),
KEY `matchNO1` (`matchNO`),
KEY `place` (`place`),
CONSTRAINT `matchNO` FOREIGN KEY (`matchNO`, `place`) REFERENCES `match` (`matchNO`, `place`),
CONSTRAINT `teamNameJ` FOREIGN KEY (`teamNameJ`) REFERENCES `team` (`teamName`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
------解决方案-------------------- FOREIGN KEY (matchNO,place) REFERENCES `match` (matchNO,place)
------解决方案--------------------KEY mp (matchNO,place),
FOREIGN KEY (matchNO,place) REFERENCES `match` (matchNO,place)
------解决方案--------------------你想实现的功能是什么?
或者改为如此
CREATE TABLE `join` (
`teamNameJ` varchar(50) NOT NULL,
`matchNO` varchar(50) NOT NULL,
`place` varchar(50) NOT NULL,
`result` varchar(50) DEFAULT NULL,
PRIMARY KEY (`teamNameJ`,`matchNO`,`place`),
KEY `matchNO` (`matchNO`),
KEY `place` (`place`),
CONSTRAINT `matchNO` FOREIGN KEY (`matchNO`) REFERENCES `match` (`matchNO`), //正常
CONSTRAINT `teamNameJ` FOREIGN KEY (`teamNameJ`) REFERENCES `team` (`teamName`),//正常
CONSTRAINT `place` FOREIGN KEY (matchNO,`place`) REFERENCES `match` (matchNO,`place`) //place外键无法插入
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;