Mysql 排除结果并使用SQL查询执行插入
表a 表组Mysql 排除结果并使用SQL查询执行插入,mysql,sql,Mysql,Sql,表a 表组 Rowid Msgid Userid 1 3 55 2 3 56 3 3 57 4 4 55 5 4 56 这里有一个表a和group表。Rowi
Rowid Msgid Userid
1 3 55
2 3 56
3 3 57
4 4 55
5 4 56
这里有一个表a
和group
表。Rowid主键
我想在表a中插入行
此查询将
在表a中插入行,即对于msgid 3,已经有55 56 57行,因此它只能插入58 59 60行
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
对于Msgid 3,我想检查表a中是否有任何关联的组成员(groupID 2),如果没有,则向其中添加一行。
添加到表a中
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
所以我不会插入userid 55,56,57,因为它已经在msgid3的表a中了。如何查询此场景请尝试下面的代码
rowid Msgid Userid
6 3 58
7 3 59
8 3 60
我认为您的插入查询是正确的
祝你好运 其实很简单:
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
您应该具有具有Msgid和Userid的唯一组合索引,以便能够在重复键上使用
INSERT IGNORE
或
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;