用下面的表違反約束上插入
CREATE TABLE `Play` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`room_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_FEBB7184A76ED395` (`user_id`),
KEY `IDX_FEBB718454177093` (`room_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE `User` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`nickname` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_2DA17977F85E0677` (`username`),
UNIQUE KEY `UNIQ_2DA17977A188FE64` (`nickname`),
UNIQUE KEY `UNIQ_2DA17977E7927C74` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `User` VALUES(1, 'user', 'nickname', '[email protected]');
CREATE TABLE `Room` (
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `Room` VALUES(1);
ALTER TABLE `Play`
ADD CONSTRAINT `play_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`),
ADD CONSTRAINT `play_ibfk_2` FOREIGN KEY (`room_id`) REFERENCES `Room` (`id`);
,並試圖運行下面的語句
INSERT INTO `Play` (`id` ,`user_id` ,`room_id`) VALUES (NULL , '1', '1')
我得到一個錯誤
#1452 - Cannot add or update a child row: a foreign key constraint fails
(`play`, CONSTRAINT `play_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`))
兩組數據,#1數據庫中存在用戶和#1房間。這怎麼會失敗?我對SQL很熟悉,但我不知道這種情況下的錯誤是什麼......
聽起來很愚蠢,但只是爲了確保當你從'User'選擇id時,你會得到什麼id ='1'? – yokoloko
那麼,如果我檢查'1',我會得到用戶。如果我檢查「1」,我自然會得到一個錯誤......但是爲什麼查詢會插入「1」呢?我使用phpMyAdmin創建它,並自動添加'''? –