2012-01-20 31 views
0

表一个排除的结果和执行与SQL查询

Rowid    Msgid  Userid 
1     3    55 
2     3    56 
3     3    57 
4     4    55 
5     4    56 

表组

RowID    GroupID   UseriD 
1      2    55 
2      2    56 
3      2    57 
4      2    58 
5      2    59 
6      2    60 
7      3    60 
8      3    55 

在这里有一个表agroup表的插入物。 ROWID主键

我想将行插入表中的

这个查询将

行插入表MSGID 3即已经存在55 56 57所以它必须只插入58 59 60 。

Insert into 
table a (msgid,Userid) 
values(@msgid,@userid) 
where userid not in table a 
where tbl_a.msgid=3 
and tbl_group.groupid = 2 

对于MSGID 3我要检查是否有在表中的相关联的任何组成员(组ID 2),如果不是则添加行到它。 即添加到表

rowid Msgid Userid 
    6  3  58 
    7  3  59 
    8  3  60 

所以我不会插入用户ID 55,56,57,因为它已经在表中的MSGID 3.如何在这种情况下

+0

你应该有MsgId和用户ID的独特组合索引,以便能够使用'INSERT IGNORE'或'对重复KEY' –

回答

0

低于尝试做一个查询代码

Insert IGNORE into 
table a (msgid,Userid) 
values(@msgid,@userid) 
where userid not in table a 
where tbl_a.msgid=3 
and tbl_group.groupid = 2 

我正在考虑,你的插入查询是正确的......

好运!

0

这其实很简单:

INSERT INTO TABLE_GROUP 
SELECT * FROM TABLE_A 
WHERE ... -- you can have or not have a where clause as you like 
ON DUPLICATE KEY UPDATE;