MYSQL 使用 2 列限定的其他表的值更新一个表

标签 mysql inner-join

我一直在努力让这个查询起作用,希望有人能给我一些建议。

我有两张 table 。主人和辅助。我需要根据 groupid 和 section id 使用 aux 中而不是 master 中的任何行更新 master。

我实际上需要对多个辅助表执行此操作,但只要我能弄清楚如何在一个表上执行此操作,我就可以在我需要的每个表上手动运行查询。

到目前为止,我一直在尝试使用 select 从 aux 中获取应该插入到 master 中的数据。一旦我有了它,我就可以修改它来创建插入查询。 (我希望)

select 
   a.id 
from 
   master as m, 
   aux as a
where 
   a.gid = m.groupid 
and 
   a.sid = m.sectionid 
and 
   not in m.groupid 
and 
   not in m.sectionid

此查询无效:(

主表

id    groupid    sectionid
1     A Group    21
2     A Group    23
3     B Group    55
4     C Group    999
5     D Group    52A
6     D Group    53

辅助表

id    gid        sid
1     A Group    21
2     A Group    22
3     A Group    23
4     B Group    55
5     B Group    55A
6     C Group    999
7     D Group    52A
8     D Group    53
9     D Group    56

查询后的主表

id    groupid    sectionid
1     A Group    21
2     A Group    23
3     B Group    55
4     C Group    999
5     D Group    52A
6     D Group    53
7     A Group    22
8     B Group    55A
9     D Group    56

提前感谢您的帮助。

最佳答案

我不认为 and not in m.groupid 是有效的 sql。 带有子选择的 not exist 应该可以解决问题:

insert into master (groupid, sectionid)
select a.gid, a.sid
from aux as a
where not exists(
  select *
  from master as m
  where m.groupid = a.gid
  and a.sid = m.sectionid
)

关于MYSQL 使用 2 列限定的其他表的值更新一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092690/

相关文章:

php - 创建深度无限多维数组

mysql - 在mysql语句中回显?

mysql - MySQL 中 4 个字节的 Unicode 字符表情符号

php - MySQL Inner Join 涉及三个表

MySQL 连接查询错误

php - 一个查询中的两个位置

php - 如何使用多个标签快速搜索帖子/列表?

php - MySQL join——分类表与数据表结合

mysql - 如何在mysql中使用内部查询获取源城市和目的地城市名称

mysql - 如何在mysql中进行多个条件的连接