I have a table name "slot_place_box". It looks like this :
- id_slot_pb (PRIMARY KEY)
- id_place_box (INT)
- date (DATE)
- hour (HOUR)
- slot_available (INT)
I have an UNIQUE index for (id_place_box + date + hour).
In PHP I'm building an SQL request, it looks like this :
$sql_request = "
INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-10', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE
SPB.id_place_box = 32 AND SPB.date = '2017-12-10' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);
INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-11', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-11' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);
INSERT INTO media.slot_place_box (id_place_box, date, hour)VALUES (32, '2017-12-12', NULL)ON DUPLICATE KEY UPDATE id_place_box = id_place_box;
SET @id = (SELECT SPB.id_slot_pb FROM media.slot_place_box as SPB WHERE SPB.id_place_box = 32 AND SPB.date = '2017-12-12' AND SPB.hour IS NULL);
INSERT INTO media.slot_config (id_config, id_slot_pb) VALUES (125, @id);
//etc
";
My problem is that my "INSERT...ON DUPLICATE KEY UPDATE" still insert a new line when I have a duplicate key (= another "slot_place_box" in the database with same "id_place_box + date + hour", so my @id get more than one result and the script bug. It just adds a row in my table for my first "INSERT" and does nothing after (when I have duplicate row).
Right now this is the clues I have :
- I added a "UNIQUE" index for the combination of "id_config + date + hour", is it enough for the "ON DUPLICATE KEY" or I absolutely need the PRIMARY KEY?
- Maybe I have trouble with my field name "date" and "hour"?
- The fact that I have a "NULL" value for "hour" maybe create some trouble with my UNIQUE indexes...
Do you have an idea why please?