且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL 查询,插入重复项的问题

更新时间:2023-01-22 17:36:58

您只需在查询中添加重复键:

insert into xf_forum_watch
    (user_id, node_id, notify_on, send_alert, send_email)
    select user_id,
    71 as node_id,
    'thread' as on notify_on,
    1 as send_alert,
    1 as send_email
    from xf_user
where user_group_id NOT IN (1, 18, 40)
on duplicate key update 
    send_alert = 1,
    send_email = 1,
    notify_on = 'thread'

这假设您设置了正确的主键唯一性,以便正确识别重复项.

This assumes that you have the proper unique of primary key set up so that duplicates are properly identified.

如果您想在 on duplicate key 子句中使用条件逻辑,那也是可能的:

If you want conditional logic in the on duplicate key clause, that’s also possible:

on duplicate key update 
    send_alert = case when send_alert = 0 then 1 else send_alert end,
    send_email = case when send_email = 0 then 1 else send_email end,
    notify_on = case when notify_on is null or notify_on = '' then  'thread' else notify_on end