【问题标题】:MySql tricky conditional in joined tables连接表中的 MySql 棘手的条件
【发布时间】:2020-06-06 08:50:45
【问题描述】:

第一个表有几个字段,但“PersonId”是唯一感兴趣的字段。 第二个表有“PersEmId”和“PersEmGr”。

mysql是:

   select  a.PersonId, b.PersEmId, b.PersEmGR
       from PersonRepDb a left join PersEm b 
       on a.PersonId = b.PersEmId
    (conditions to be figured out)    

无条件输出为:

1   ABBOT.LE00  ABBOT.LE00  betty  
2   ABBOT.LE00  ABBOT.LE00  flutes  
3   ACKERBRO00      

所以我们看到 ABBOT.LE 分为“贝蒂”和“长笛”两组,而 ACKERBR000 没有任何组。

如果条件是: where PersEmGr = 'flutes' 查询只返回 ABBOT.LE00,这是正确的。

但是,我想知道谁不在“长笛”中。如果条件是

where PersEmGr != 'flutes' OR PersEmGr  IS NULL

查询返回

1   ABBOT.LE00  ABBOT.LE00  betty <br>
2   ACKERBRO00      

ABBOT.LE00 出现在这里是因为虽然他在 'flutes' 中,但他也在 'betty' 中,这填补了条件的 != 'flutes' 部分。

任何人都可以提出一种编写条件的方法,以便查询可以选择不在长笛中的每个人,无论他们是否在另一个组中。

【问题讨论】:

    标签: mysql sql join left-join where-clause


    【解决方案1】:

    将条件放在ON 子句中。

    select  a.PersonId, b.PersEmId, b.PersEmGR
    from PersonRepDb a 
    left join PersEm b on a.PersonId = b.PersEmId AND b.PersEmGR = 'flutes'
    WHERE b.PersEmId IS NULL
    

    【讨论】:

    • 我喜欢它。永远不会想到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    相关资源
    最近更新 更多