-1

I have the following table: enter image description here

As you can see, date and bed form a composite primary key.

I am trying to run this query:

INSERT INTO days (date, operating_time, bed) VALUES ('2016-11-07', 6.55, 1) ON duplicate key update operating_time=VALUES(operating_time);

The problem is that it seems to update based only on the date column. So for example, running the above query for a bed value of 1, and then re-running it but with a bed value of 2 will actually update the original record (the one where bed = 1)

How can I make the ON DUPLICATE KEY statement check both the date and bed columns?

Edit

Here is the create statement for the table:

CREATE TABLE `days` (
  `date` date NOT NULL,
  `operating_time` float DEFAULT '0',
  `bed` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`date`,`bed`),
  UNIQUE KEY `date_UNIQUE` (`date`),
  KEY `bed_idx` (`bed`),
  KEY `date` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Matthew Goulart
  • 2,873
  • 4
  • 28
  • 63

2 Answers2

2

The table days has a UNIQUE index on date so if you do an INSERT with a same date but different bed, it won't be inserted because of the UNIQUE (else it fails the unique index).

If you try inserting with the same bed and date (but different operating_time), it will make an UPDATE.

barudo
  • 665
  • 4
  • 13
0

After posting the create statement for the table, it because evident that the UNIQUE key was composed of only the date column. After adding the bed column, it worked as expected. I will need to read up on the different types of keys and why specifically the UNIQUE key must contain both columns used in the composite key.

Matthew Goulart
  • 2,873
  • 4
  • 28
  • 63