从表中插入缺失的记录

时间:2013-04-01 13:50:32

标签: mysql

我有两个表users (id,用户名等等)user_contacts (id,userid,contactid等...)

鉴于我的user代码为84,为了将缺少的记录插入user_contacts以关联user 84,最有效的查询是什么?所有其他用户?

1 个答案:

答案 0 :(得分:1)

鉴于您最近的评论,这应该有效:

insert into user_contacts (userid, contactid)
select u.id, 84
from users u 
   left join user_contacts uc on u.id = uc.userid and uc.contactid = 84
where uc.id is null

这将在user_contacts表中为当前没有contactid 84行的每个用户插入一行。请务必正确指定列。

或者,您可以使用NOT INNOT EXISTS。例如,

insert into user_contacts (userid, contactid)
select u.id, 84
from users u
where u.id not in (
    select userid 
    from user_contacts 
    where contactid = 84)
相关问题