SQL加入和排除/过滤

时间:2015-09-17 13:57:22

标签: mysql sql

我有一个连接2个表的SQL查询,我正在尝试过滤符合条件的行,如果相同的条件与不同的值匹配则过滤掉结果,但最后的WHERE子句似乎被忽略:

SELECT DISTINCT
    tblclients.firstname, tblclients.lastname, tblclients.email
FROM
    tblclients
LEFT JOIN
    (
        SELECT *
        FROM tblhosting
        WHERE tblhosting.packageid IN (75,86)
    ) tblhosting ON tblclients.id = tblhosting.userid
WHERE 
    tblhosting.packageid NOT IN (76,77,78)

想法是获得具有特定包裹(ID 75和86)的客户列表,然后排除/取出任何具有另一个包裹以及75/86(ID 76,77, 78等)。虽然根本没有排除那些结果,但在Stackoverflow上尝试了很多变化,我在哪里出错?

3 个答案:

答案 0 :(得分:2)

将其添加到join条件本身。如果您有where子句过滤器,则join将被视为inner join

tblhosting ON tblclients.id = tblhosting.userid and tblhosting.packageid NOT IN (76,77,78)

答案 1 :(得分:1)

在这种情况下我根本不会使用LEFT JOIN。我会使用EXISTSNOT EXISTS的组合来获得您想要的结果。

SELECT DISTINCT c.firstname, c.lastname, c.email
  FROM tblclients c
 WHERE EXISTS (SELECT *
                 FROM tblhosting h
                WHERE h.userid = c.id
                  AND h.packageid IN (75,86))
   AND NOT EXISTS (SELECT *
                     FROM tblhosting h
                    WHERE h.userid = c.id
                      AND h.packageid IN (76,77,78))

答案 2 :(得分:0)

如果没有错,这就是你要找的东西

SELECT tblclients.firstname, tblclients.lastname, tblclients.email
FROM
    tblclients
LEFT JOIN
    (
     SELECT userid
        FROM tblhosting
        WHERE tblhosting.packageid IN (75,86,76,77,78)
    group by  userid
   having count(1) = count(case when packageid IN (75,86) then 1 end)
) tblhosting  
ON tblclients.id = tblhosting.userid