每当我插入tblprowareinventory
时,我想在tblprowareproducts
中添加一个外键:
CREATE TABLE `tblprowareproducts` (
`ItemID` int(11) NOT NULL,
`ItemCode` varchar(30) NOT NULL,
`itemDescription` varchar(60) NOT NULL,
`Strand` varchar(30) NOT NULL,
`UnitCost` double NOT NULL,
`SaleCost` double NOT NULL,
`CategoryID_fk` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tblprowareproducts`
ADD PRIMARY KEY (`ItemID`),
ADD KEY `CategoryID_fk` (`CategoryID_fk`);
ALTER TABLE `tblprowareproducts`
MODIFY `ItemID` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `tblprowareproducts`
ADD CONSTRAINT `tblprowareproducts_ibfk_1` FOREIGN KEY (`CategoryID_fk`) REFERENCES `tblprowarecategory` (`PCategoryID`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
tblProwareinventory
CREATE TABLE `tblprowareinventory` (
`inventoryID` int(11) NOT NULL,
`ItemID_FK` int(11) NOT NULL,
`DateOfInventory` date NOT NULL,
`CurrentQuantity` int(11) NOT NULL,
`TotalQuantity` int(11) NOT NULL,
`DeliveredQuantity` int(11) NOT NULL,
`PhysicalCount` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tblprowareinventory`
ADD PRIMARY KEY (`inventoryID`),
ADD KEY `ItemID_FK` (`ItemID_FK`);
ALTER TABLE `tblprowareinventory`
ADD CONSTRAINT `tblprowareinventory_ibfk_2` FOREIGN KEY (`ItemID_FK`) REFERENCES `tblprowareproducts` (`ItemID`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
INSERT INTO tblprowareinventory(ItemID_FK)
VALUES ((SELECT ItemID FROM tblprowareproducts))
但是我收到了这个错误:
答案 0 :(得分:1)
您可以使用以下CREATE TRIGGER
声明:
DELIMITER //
CREATE DEFINER = `root`@`localhost` TRIGGER AddToInventory AFTER INSERT ON tblprowareproducts
FOR EACH ROW
BEGIN
INSERT INTO tblprowareinventory (ItemID_FK) VALUES (NEW.ItemID);
END;//
DELIMITER ;
注意:您必须删除phpMyAdmin上的当前触发器或使用以下语句:DROP TRIGGER AddToInventory;
才能成功运行此CREATE TRIGGER
语句。
TRIGGER
使用tblprowareinventory
成功向NEW.ItemID
表添加新行,但您在PRIMARY KEY
inventoryID
上定义了tblprowareinventory
表。没关系,但在INSERT
表上尝试tblprowareinventory
第二行后,您应该收到错误:
#1062 - 重复输入' 0'关键' PRIMARY'
TRIGGER
尝试INSERT
tblprowareinventory
表上的第二行,inventoryID
列为0。这是不可能的,因为0只能在inventoryID
列上存在一次。
您也可以使用AUTO_INCREMENT
列上的inventoryID
解决此问题:
ALTER TABLE `tblprowareinventory` MODIFY `inventoryID` INT(11) NOT NULL AUTO_INCREMENT;
要INSERT
tblprowareproducts
表上的INSERT INTO `tblprowareproducts` (`ItemID`, `ItemCode`, `itemDescription`, `Strand`, `UnitCost`, `SaleCost`, `CategoryID_fk`)
VALUES (NULL, '111', '111', '111', '1', '1', '1')
新行,我使用了以下语句:
// Gets a list of multiple users.
function getdata(){
$query = $this->db->get('users');
return $query->result_array();
}
// Gets the users information
public function getUserInfo($user_id) {
$this->db->where('user_id', $user_id);
$query = $this->db->get('users');
return $query->row_array();
}