Insert New Row in Table 3 if combination of Col A and Col B in Table C Don't Exist

二次信任 提交于 2019-12-07 20:50:39

问题


I have a code that gets data from Tables 1 and 2, and then inserts new rows into Table 3. My problem is that the code adds records that already exist. How can I prevent duplicate errors from being inserted, when the combination of groupid and userid in Table C already exists?

INSERT INTO mdl_groups_members (groupid,userid)
SELECT l.mgroup AS moodle, r.id AS mdl_user  
    FROM moodle AS l 
    JOIN mdl_user AS r   
        ON l.orders_id = r.id
WHERE l.mgroup > 0

Here's the table before I ran the script:

id  groupid userid  timeadded
1   1       1       1372631339
2   4       2       1372689032
3   8       3       1373514395
4   3       4       1373514395

Here's the table after I ran the script. I placed a "*" next to the duplicated rows that I don't want to insert.

id  groupid userid  timeadded
1   1       1       1372631339
2   4       2       1372689032
3   8       3       1373514395
4   3       4       1373514395
*5  1       1       1372631339
*6  4       2       1372689032
*7  8       3       1373514395
*8  3       4       1373514395
9   2       6       1373514398

I've tried many of the solutions on this site, but none have worked. I welcome all advice.

Thanks, Matt


回答1:


If you want to avoid duplicates, then add a unique index or constraint:

create unique index idx_mdl_groups_members_2 on mdl_groups_members(groupid, userid)

Then use on duplicate key update:

INSERT INTO mdl_groups_members (groupid, userid)
    SELECT l.mgroup AS moodle, r.id AS mdl_user  
    FROM moodle l JOIN
         mdl_user r   
         ON l.orders_id = r.id
    WHERE l.mgroup > 0
    ON DUPLICATE KEY UPDATE groupid = VALUES(groupid);

The on duplicate key update causes the insert to ignore duplication errors, inserting other rows with no problems.



来源:https://stackoverflow.com/questions/29688712/insert-new-row-in-table-3-if-combination-of-col-a-and-col-b-in-table-c-dont-exi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!