Insert Into.. Select.. On Duplicate Key Update

446 views Asked by At

I'm trying to test how the insert into duplicate key works. And currently this is what I did:

INSERT INTO
user_test (userName, first, last)

SELECT
u.userName, u.first, u.last
FROM otherdatabase.user as u

ORDER BY u.userName ASC

ON DUPLICATE KEY UPDATE
userName = u.userName

I executed this query and it worked and inserted rows. Then what I did was I modified one row from the user table and then tried to run this query again, but instead of just updating that one row it inserted all the rows again.

From what I understand shouldn't it just update that one row I modified from the user table?

What I'm trying to do is do a "Insert if it doesn't exist and update if it exist" query and found that using insert into .. on duplicate key can do that but I'm obviously doing it wrong...

CREATE TABLE user_test (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  userName varchar(20) DEFAULT NULL,
  first varchar(20) DEFAULT NULL,
  last varchar(20) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=latin1 

Per Barranka's suggestion I added a unique index to the user_name column

Alter table user_test add unique index idx_userName(userName)

Then I ran the query again and it didn't add any more rows since its already existing.. This is an example of what the user_table looks like now, its now the same on the users table.

user_table:

userName    |   first   |   last    |
ckeith      |   Carl    |   Keith   |
mmonroe     |   Mickey  |   Monroe  |

Then what I did to test it again is from the user table I modified one of the rows

user:

userName    |   first   |   last    |
ckeithh     |   Carl    |   Keith   |
mmonroe     |   Mickey  |   Monroe  |

and executed the query again, this is now what the users_table looks like:

user_table:

userName    |   first   |   last    |
ckeith      |   Carl    |   Keith   |
mmonroe     |   Mickey  |   Monroe  |
ckeithh     |   Carl    |   Keith   |

I thought it would just update the first row to ckeithh but it just inserted one row? My expected output was:

user_table:

userName    |   first   |   last    |
ckeithh     |   Carl    |   Keith   |
mmonroe     |   Mickey  |   Monroe  |

Update:

I added a unique index and made sure that it is unique. The inserting works but now the update is not working. Anything else i should try?


Still not able to get this to work, I have confirmed that the column i'm using is unique and that my version of mysql is v5 (i saw on one of the forums that for this to work mysql should be v5, not sure if thats real or not, but still i checked and im using v5.5.37)

0

There are 0 answers