很多業(yè)務(wù),尤其多對(duì)多關(guān)聯(lián),插入中間關(guān)系表數(shù)據(jù)時(shí),經(jīng)常會(huì)出現(xiàn)重復(fù)插入的問題。常用的解決方案有:
- 插入前刪除全部關(guān)聯(lián)數(shù)據(jù)
- 插入前提前查詢數(shù)據(jù)是否存在
- 使用復(fù)合主鍵
這里再增加一個(gè)就是在insert時(shí)加入where條件限定,如Oracle中一個(gè)表User,有id(主鍵,使用序列test_id)、name,通過name來判斷是否重復(fù):
insert into member(name)
select nextval('TEST_ID'),'name' from USER
where not exists(select ID from USER where NAME = 'name');