转换NOT IN为LEFT JOIN

时间:2019-02-11 11:42:36

标签: mysql sql

我有这个查询:

SELECT id from patients_member where id NOT IN
(SELECT msc.member_id 
    FROM journeys_memberstagechallenge msc
    WHERE msc.challenge_id = '2ab9a76c1ad211e7a1350242ac110003'
          AND msc.completed_date IS NOT NULL);

我需要更新此查询,以便它仅具有左联接和条件,以便我的代码生成器可以自动生成它。 请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作。

SELECT t1.id 
FROM   patients_member t1 
       LEFT JOIN journeys_memberstagechallenge t2 
              ON t2.member_id = t1.id 
                 AND t2.challenge_id = '2ab9a76c1ad211e7a1350242ac110003' 
                 AND t2.completed_date IS NOT NULL 
WHERE  t2.member_id IS NULL 

答案 1 :(得分:0)

这看起来像:

select pm.id
from patients_member pm left join
     journeys_memberstagechallenge msc
     ON msc.member_id = pm.id and
        msc.challenge_id = '2ab9a76c1ad211e7a1350242ac110003' and
        msc.completed_date is not null
where msc.member_id is null;

第二个表上的条件放在on子句中。 where子句-检查是否匹配-实现not in条件。