I have this table:
create table comment_check (
record_id int ( 10 ) unique not null AUTO_INCREMENT ,
member_id int (10) not null unique ,
has_question_comment bool ,
has_business_comment bool
);
And this upsert:
INSERT INTO comment_check
(member_id , has_question_comment )
VALUES
(4815162342, 1 )
ON DUPLICATE KEY UPDATE
has_question_comment = 1
But what I am confused about is I have two keys, the record_id , and the member_id which is the real key. When I create the table, should I label the member_id column as key? And how can I distinguish between the two keys (member_id and record_id) in the query?
Thanks!
There is no need to distinguish between them.
Whichever key throws a “duplicate key” exception will be the one that MySQL uses for the update.
In your case, since you are not providing a value for the
record_idcolumn, and that column is defined as AUTO_INCREMENT, MySQL is going to generate a unique value for that column. So, it’s not possible that your statement will cause a “duplicate key” exception on the record_id column.It will be the “member_id” column that throws the duplicate key exception, so MySQL will perform an update equivalent to:
Actually, the value supplied for member_id in your statement will likely be interpreted as 2147483647, given that the value exceeds the maximum value for an INT.
In the more general case, where either column would throw a duplicate key exception, e.g.
either of the two columns can throw a “duplicate key” exception, the behavior (AFAIK) is not well well defined as to which row will get updated, whether its:
-or-
I believe it depends on which error gets thrown first. And the MySQL specification (AFAIK) does not specify the order in which those unique constraints gets checked. (It may differ based on the storage engine.)