【问题标题】:MYSQL Update one table with the values other table qualified using 2 columnsMYSQL 使用其他表使用 2 列限定的值更新一个表
【发布时间】:2015-05-07 05:36:03
【问题描述】:

我一直试图让这个查询工作,希望有人能给我一些建议。

我有两张桌子。主和辅助。我需要根据 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

提前感谢您的帮助。

【问题讨论】:

  • 试试我的回答,如果您需要一个用于多个表,请告诉我。

标签: mysql inner-join


【解决方案1】:

我不认为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
)

【讨论】:

  • 很好的答案,感谢您对我的建议。我只是碰巧在你之前 1 分钟得到它。 :) 我至少给了你一个赞成票
【解决方案2】:

你能试试这个吗...

select 
    id 
from 
    aux as a
where 
    not exists (
        select 
            id 
        from 
            master 
        where 
            groupid = a.gid 
        and 
            sectionid = a.sectionid
    )

SQLFiddle

【讨论】:

  • 哇,真快!我去试试。
  • 为什么你希望它不存在不同的行?您希望它不存在相同的行。
  • 此查询将不返回任何结果。另一个表中总会存在不同的行。见我上面的回答。
  • 谢谢它的工作,我不得不改变一下,但它工作:)
  • 很高兴我能帮上忙。抱歉,查询有点混乱,但很高兴它对您有用。 :)
猜你喜欢
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 2015-05-19
相关资源
最近更新 更多