MySQL Update on duplicate error - mysql

I have two tables, EVENTS and EVENT_ATTENDEES.
I'd like to be able to attempt a row insert on event_attendees and if the call_sign and event_id already exist in the table, it should update the response for that row instead of inserting a new one.
Events Table
CREATE TABLE `events` (
`event_id` int(11) NOT NULL,
`created_by` varchar(1000) NOT NULL,
`event_type` varchar(1000) NOT NULL,
`event_name` varchar(1000) NOT NULL,
`event_start` datetime NOT NULL,
`event_end` datetime NOT NULL,
`max_attendees` varchar(10) NOT NULL,
`open_registration` varchar(10) NOT NULL
)
ALTER TABLE `events`
ADD PRIMARY KEY (`event_id`);
ALTER TABLE `events`
MODIFY `event_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11
Event Attendees
CREATE TABLE `event_attendees` (
`id` int(11) NOT NULL,
`event_id` int(11) NOT NULL,
`call_sign` varchar(10) NOT NULL,
`response` varchar(10) NOT NULL
)
ALTER TABLE `event_attendees`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `event_id_2` (`event_id`,`call_sign`),
ADD KEY `event_id` (`event_id`) USING BTREE;
ALTER TABLE `event_attendees`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
ALTER TABLE `event_attendees`
ADD CONSTRAINT `event_id_fk` FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
I have tried the below query, but constantly get an error (I have created an event that has event_id = 10):
INSERT INTO event_attendees
(event_id, call_sign, response)
VALUES
('10', '007', 'Declined')
ON DUPLICATE KEY UPDATE
response = VALUES('Declined')
" #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test')' at line 6"

There is no need of VALUES here. Modify your query as:
INSERT INTO event_attendees
(event_id, call_sign, response)
VALUES
('10', '007', 'Declined')
ON DUPLICATE KEY UPDATE
response = 'Declined'
From doc:
you can use the VALUES(col_name) function to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement
Here you can find more about VALUES function.

Related

Foreign Key Failure #1452 MariaDB PhpMyAdmin Mysql

got a slight problem with my constraint I wanna add to my tables:
so first at all my tables:
DROP TABLE IF EXISTS `Sales`;
CREATE TABLE IF NOT EXISTS `Sales` (
`ItemNo` int(11) NOT NULL,
`Model` varchar(100) NOT NULL unique,
`PurchasingPrice` decimal(11,2) NOT NULL,
`ManufNo` int(11) Not Null,
`LocNo` int(11) NOT NULL,
`SuppNo` int(11) NOT NULL,
`CatNo`int(11) NOT NULL,
`UnitPrice`decimal (11,2),
PRIMARY KEY (`ItemNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `Sales` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`Unitprice`) VALUES
(1,'Tieflader 18t',6969.84,4,1,6,2,9582.56),
(2,'Betonmischer-3m³',47829.00,3,2,3,3,82457.23),
(3,'Lastenkran 800kg',4129.00,2,2,2,3,8466.43),
(4,'Hubwagen,10m',9478.00,1,2,3,3,18457.84);
DROP TABLE IF EXISTS `Rent`;
CREATE TABLE IF NOT EXISTS `Rent` (
`ItemNo` int(11) NOT NULL, ( Different Number-Area like 1000+, very small project)
`Model` varchar(100) NOT NULL unique,
`PurchasingPrice` decimal(11,2) NOT NULL,
`ManufNo` int(11) Not Null,
`LocNo` int(11) NOT NULL,
`SuppNo` int(11) NOT NULL,
`CatNo`int(11) NOT NULL,
`PricePerDay`decimal (11,2),
`RentDateNo`int(11),
`AdressNo` int(11),
PRIMARY KEY (`ItemNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `RENT` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`PricePerDay`,`RentDateNo`,`AdressNo`) VALUES
(1000,'Betonmischer 50l',123.45,4,1,6,2,42.56,2,1),
(1001,'Winkelschleifer 800 Watt³',29.00,3,2,3,3,17.23,3,1),
(1002,'Akkuschrauber 12V',129.00,2,2,2,3,16.43,1,2),
(1003,'Akkuschrauber 18V',178.00,1,2,3,3,21.84,1,2);
DROP TABLE IF EXISTS `Stock`;
CREATE TABLE IF NOT EXISTS `Stock` (
`ItemNo` int(11) NOT NULL,
`Min-Stock` int(11) Not Null,
`Current-Stock` int(11) Not Null,
`Max-Stock` int(11) Not Null,
PRIMARY KEY (`ItemNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `Stock` (`ItemNo`,`Min-Stock`,`Current-Stock`,`Max-Stock`) VALUES
(1000,0,1,1),
(1001,0,1,1),
(1002,0,0,1),
(1003,0,1,1),
(1,2,5,8),
(2,1,2,2),
(3,3,6,9),
(4,1,3,4);
When I try to add an constraint FK with:
ALTER TABLE `Stock`
ADD CONSTRAINT `sales_stock_fk` FOREIGN KEY (`ItemNo`) REFERENCES `sales`(`ItemNo`) ON DELETE RESTRICT ON UPDATE RESTRICT,
ADD CONSTRAINT `rent_stock_fk` FOREIGN KEY (`ItemNo`) REFERENCES `rent`(`ItemNo`) ON DELETE RESTRICT ON UPDATE RESTRICT;
it does Fail. When I delete all Numbers which aren't from the sales Table I can use this one:
ALTER TABLE `Stock`
ADD CONSTRAINT `sales_stock_fk` FOREIGN KEY (`ItemNo`) REFERENCES `sales`(`ItemNo`) ON DELETE RESTRICT ON UPDATE RESTRICT;
and can also add new items in the sales table as wanted and the new in stock. But I can't add Stocks for rent items and also the combined Add Constraint with both tables at once don't work. I am not sure how to get it work that I can add my Items to the table. I always get the #1452 child table failure.
Maybe someone can help me an know how to handle it.
The result should be: I got to the table stock and hover over an ItemNo and when I click it I should be forwarded to table sales if ItemNo is from sales or rent if from rent. I am using Xampp phpmyadmin, MariaDB
So the error is Cannot add or update a child row: a foreign key constraint fails you should change values the Sales table on ItemNo change it before 1 to 1000 and more
your value is
INSERT INTO `Sales` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`Unitprice`) VALUES
(1,'Tieflader 18t',6969.84,4,1,6,2,9582.56),
(2,'Betonmischer-3m³',47829.00,3,2,3,3,82457.23),
(3,'Lastenkran 800kg',4129.00,2,2,2,3,8466.43),
(4,'Hubwagen,10m',9478.00,1,2,3,3,18457.84);
Change it to :
INSERT INTO `Sales` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`Unitprice`) VALUES
(1000,'Tieflader 18t',6969.84,4,1,6,2,9582.56),
(1001,'Betonmischer-3m³',47829.00,3,2,3,3,82457.23),
(1002,'Lastenkran 800kg',4129.00,2,2,2,3,8466.43),
(1003,'Hubwagen,10m',9478.00,1,2,3,3,18457.84);

Auto increment Id value increased by 1 after insert trigger

I have 3 tables as below:
CREATE TABLE `user_dummy` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(50) NOT NULL,
`user_email` VARCHAR(100) NOT NULL,
PRIMARY KEY (`user_id`)
)
ENGINE=InnoDB
;
CREATE TABLE `user_role` (
`user_role_id` INT(11) NOT NULL AUTO_INCREMENT,
`user_role_name` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`user_role_id`)
)
ENGINE=InnoDB
;
CREATE TABLE `user` (
`user_seq` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`user_name` VARCHAR(50) NOT NULL,
`user_email` VARCHAR(100) NOT NULL,
`user_role_id` INT(11) NOT NULL,
PRIMARY KEY (`user_seq`),
INDEX `FKh2wc2dtfdo8maylne7mgubowq` (`user_role_id`),
CONSTRAINT `FKh2wc2dtfdo8maylne7mgubowq` FOREIGN KEY (`user_role_id`) REFERENCES `user_role` (`user_role_id`) ON UPDATE CASCADE ON DELETE CASCADE
)
ENGINE=InnoDB
;
I have created after insert trigger on user table.
i.e., when I insert 1 record into user_dummy table, it will insert records into table user table with all mappings of user_role.
trigger:
CREATE TRIGGER `user_dummy_after_insert` AFTER INSERT ON `user_dummy` FOR EACH ROW BEGIN
INSERT INTO user(user_id, user_name, user_email, user_role_id)
SELECT NEW.user_id, NEW.user_name, NEW.user_email, user_role_id
FROM user_role;
END
Above trigger is able to insert records into user table but the auto_increment value is incremented by 1 after each user_role record.
If you observe user_seq 3 is missing. And after inserting 4 records, auto_increment value set by trigger as 7.
How to fix this ?
Just an alternative: Better you could use the count function to count the total existing records and then increase it by one and assign according as. If you are interested to preserve the insertion sequence.

Insert GENERATED ALWAYS as in SQL

I created a table like this:
CREATE TABLE `group` (
`g_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`owner_id` int(10) unsigned NOT NULL,
`g_name` varchar(45) NOT NULL,
`refer_code` varchar(45) GENERATED ALWAYS AS (concat(`g_name`)) VIRTUAL,
`created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`row_hash` varchar(256) NOT NULL,
PRIMARY KEY (`g_id`),
UNIQUE KEY `g_hash_UNIQUE` (`row_hash`),
UNIQUE KEY `refer_UNIQUE` (`refer_code`),
KEY `owner_idx` (`owner_id`),
CONSTRAINT `owner_id` FOREIGN KEY (`owner_id`) REFERENCES `user` (`u_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The update statement gives me error:
INSERT INTO `server`.`group` (`owner_id`, `g_name`, `refer_code`, `created_on`, `row_hash`)
VALUES ('4', 'cool', null, '2018-02-13 10:34:11', '452345324')
Error Code: 3105. The value specified for generated column 'refer_code' in table 'group' is not allowed.
How to specify the refer_code while inserting?
Values of the generated column are computed from the expression in the column definition of your CREATE TABLE, so don't include it in INSERT or UPDATE statements:
INSERT INTO `server`.`group` (`owner_id`, `g_name`, `created_on`, `row_hash`)
VALUES ('4', 'cool', '2018-02-13 10:34:11', '452345324')

MySQL trigger insert after insert into another table

I want to add a foreign key into tblprowareinventory whenever I insert into tblprowareproducts:
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))
but I get this error:
You can use the following CREATE TRIGGER statement:
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 ;
Note: You have to remove your current trigger on phpMyAdmin or with the following statement: DROP TRIGGER AddToInventory; to successfully run this CREATE TRIGGER statement.
The TRIGGER successfully add a new row to the tblprowareinventory table with the NEW.ItemID, but you defined a PRIMARY KEY on the inventoryID of tblprowareinventory table. That's OK, but after trying INSERT a second row on tblprowareinventory table, you should get an error:
#1062 - Duplicate entry '0' for key 'PRIMARY'
The TRIGGER tries to INSERT a second row on tblprowareinventory table with 0 on the inventoryID column. This is not possible because 0 can only exists once on the inventoryID column.
You can solve this issue using a AUTO_INCREMENT on the inventoryID column too:
ALTER TABLE `tblprowareinventory` MODIFY `inventoryID` INT(11) NOT NULL AUTO_INCREMENT;
To INSERT a new row on tblprowareproducts table I used the following statement:
INSERT INTO `tblprowareproducts` (`ItemID`, `ItemCode`, `itemDescription`, `Strand`, `UnitCost`, `SaleCost`, `CategoryID_fk`)
VALUES (NULL, '111', '111', '111', '1', '1', '1')

Mysql autoincrement error when insert a new register

I have this table
CREATE TABLE IF NOT EXISTS `test`.`Challenge` (
`idChallenge` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`description` VARCHAR(45) NULL DEFAULT NULL,
`start` DATETIME NOT NULL,
`ending` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`idChallenge`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC))
ENGINE = InnoDB;
When I try insert a new register:
insert into challenge (name, start) values ("test", now());
Gives me this error:
Error Code: 1364. Field 'id_challenge' doesn't have a default value
But first I don't have this column in my table and if I put it is create.
Us must use backticks ` for reserved words.
insert into Challenge (`name`, `start`) values ("test", now());
The problem are with idChallenge, if I change it to idchallenge works.