我正在尝试将accountID
表中的accounts
字段连接到customers
表中的外键。到目前为止这是我的代码:
CREATE TABLE IF NOT EXISTS `items` (
`id` int(6) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `accounts` (
`accountID` int(6) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(200) NOT NULL,
`passwordHash` varchar(200) NOT NULL,
PRIMARY KEY (`accountID`) ) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `customers` (
`customerID` int(6) unsigned NOT NULL,
`firstName` varchar(200) NOT NULL,
`lastName` varchar(200) NOT NULL,
`address` varchar(200) NOT NULL,
`accountID` int(6) unsigned NOT NULL,
PRIMARY KEY (`customerID`),
CONSTRAINT `FK_accounts_accountID` FOREIGN KEY (`accountID`)
REFERENCES `accounts` (`accountID`) );
CREATE TABLE IF NOT EXISTS `orders` (
`id` int(6) unsigned NOT NULL,
`date` DATE NOT NULL,
`customerID` int(6) unsigned NOT NULL,
`paymentAmmount` float(6) unsigned NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_customers_customerID` FOREIGN KEY (`customerID`)
REFERENCES `customers` (`customerID`) );
CREATE TABLE IF NOT EXISTS `items-orders` (
`id` int(6) unsigned NOT NULL,
`itemId` int(6) unsigned NOT NULL,
`orderId` int(6) unsigned NOT NULL,
`itemQuantity` int(1) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_items_itemId` (`itemId`),
CONSTRAINT `FK_items_itemId` FOREIGN KEY (`itemId`) REFERENCES `items`
(`id`) ) DEFAULT CHARSET=utf8;
INSERT INTO `items` (`id`, `name`) VALUES
('1', 'super cool huge bell'),
('2', 'iron 20p D&D cube'),
('3', 'Dumbledore wand'),
('4', 'super cool small bell');
INSERT INTO `accounts` (`accountID`, `email`, `passwordHash`) VALUES
('1', 'emailAddress', 'lfadaw'),
('2', 'anotherAddress', 'dafaegdwa'),
('3', 'anotherOne', 'gaeeaw');
INSERT INTO `customers`
(`customerID`, `firstName`, `lastName`, `address`) VALUES
('1', 'moshe', 'rubin', 'haifa'),
('2', 'tanya', 'shelomayev', 'netanya'),
('3', 'itamar', 'ofer', 'haifa');
INSERT INTO `orders` (`id`, `date`, `customerID`, `paymentAmmount`) VALUES
('1', '2019-02-01', '1', '40'),
('2', '2019-02-01', '3', '361'),
('3', '2018-10-14', '2', '10');
INSERT INTO `items-orders` (`id`,`itemId`,`orderId`,`itemQuantity`) VALUES
('1', '1', '3', '2'),
('2', '4', '3', '10'),
('3', '3', '1', '1'),
('4', '2', '2', '1');
我将AUTO_INCREMENT
添加到accountID
字段,但我仍然收到此错误消息:Field 'accountID' doesn't have a default value
。
当我在表customerID
和orders
之间链接customers
字段时,我没有收到错误。
我确定这是一个之前得到解答的问题,但我发现的只是将AUTO_INCREMENT添加到字段的提示,这对我不起作用。任何帮助将被appriciated ^^
这是因为你的customer
表包含accountID
列但约束NOT NULL
并且没有默认值。
因此,实际上这是导致问题的声明:
INSERT INTO `customers`
(`customerID`, `firstName`, `lastName`, `address`) VALUES
('1', 'moshe', 'rubin', 'haifa'),
('2', 'tanya', 'shelomayev', 'netanya'),
('3', 'itamar', 'ofer', 'haifa');