简体   繁体   中英

MySQL unique key not working as expected with multiple columns containing a primary key

I have the following table

table `thing` {
    id
    other_id
    another_id
    text
    primary key (id)
    unique key (id, other_id, another_id)
}

Data

id | other_id | another_id | text
---|----------|------------|---------------
4  | 1        | 3          | This is text
5  | 1        | 3          | More text

Then I run the following query

INSERT INTO thing (id, other_id, another_id, text) VALUES ('5','1','4','A new row')
ON DUPLICATE KEY UPDATE
    text = VALUES(text)

Instead of a new row being inserted (as the values 5,1,4 are unique) the row with ID 5 is updated with the new text.

Its as if the unique key is being ignored.

It's the primary key that identify a line as unique and define if your erase (on your case, update) or add a new line. The "unique index" one is just for perf/data integrity.

You need a composite primary key aka primary key (id, other_id, another_id) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM