sql - MYSQL: Getting existing primary key when inserting record with duplicate unique key? -


i've got mysql database table has both auto-increment primary key , unique string valued key (a sha-1 hash).

if try add record has same sha-1 hash existing record, want primary key of existing record. can use "insert ... on duplicate key update" or "insert ignore" prevent exception when trying insert record existing hash value.

however, when happens, need retrieve primary key of existing record. can't find way single sql statement. if matters, code in java , i'm using jdbc.

alternatively, can 2 statements (either query followed insertion if not found, or insertion followed query if duplicate key exists). presume single statement more efficient.

if try add record has same sha-1 hash existing record, want primary key of existing record. can use "insert ... on duplicate key update" or "insert ignore" prevent exception when trying insert record existing hash value.

if have unique index on column, no matter tried, rdms not allow duplicates in column (except null value).

as said, there solution prevent "error" if appends. insert ignore in case.

anyway, insert , update modify database. mysql never return values these statements. way read db use select statement.


here "workaround" simple, since have unique column:

insert ignore tbl (pk, sha_key) values ( ... ), ( ... ); select pk, sha_key tbl sha_key in ( ... ); --                                             ^^^ --             here list of sha1 keys *tried* insert 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -