1

我有两张桌子:

所有国家

╔════╦═════════════╗
║ ID ║   COUNTRY   ║
╠════╬═════════════╣
║  1 ║ USA         ║
║  2 ║ China       ║
║  3 ║ India       ║
║  4 ║ France      ║
║  5 ║ UK          ║
║  6 ║ Australia   ║
║  7 ║ Philippines ║
╚════╩═════════════╝

支持的国家

╔════════════╦═══════════╦═══════════╗
║ COUNTRY_ID ║  COUNTRY  ║ FILTER_ID ║
╠════════════╬═══════════╬═══════════╣
║          1 ║ USA       ║         1 ║
║          2 ║ China     ║         1 ║
║          3 ║ India     ║         1 ║
║          4 ║ France    ║         2 ║
║          1 ║ USA       ║         2 ║
║          6 ║ Australia ║         2 ║
╚════════════╩═══════════╩═══════════╝

询问:

SELECT a.* 
FROM all_countries a
LEFT JOIN supported_countries s
  ON a.id = s.country_id
WHERE s.country_id IS NULL;

所以按照上面的例子我应该得到。

UK
Philippines

它工作正常,但是如果我过滤国家示例,我选择过滤 = 2。我得到零结果。

SELECT a.* 
FROM all_countries a
LEFT JOIN supported_countries s
  ON a.id = s.country_id
WHERE s.filter = 2 AND s.country_id IS NULL;

应该是我想得到这个结果,如果过滤器 = 2。

╔════╦═════════════╗
║ ID ║   COUNTRY   ║
╠════╬═════════════╣
║  2 ║ China       ║
║  3 ║ India       ║
║  5 ║ UK          ║
║  7 ║ Philippines ║
╚════╩═════════════╝

我在做正确的查询吗?

4

1 回答 1

2

ON在子句上添加条件,

SELECT  a.* 
FROM    all_countries a
        LEFT JOIN supported_countries s
           ON a.id = s.country_id AND 
              s.filter_ID = 2        -- <<=== HERE
WHERE   s.country_id IS NULL;

结果:

╔════╦═════════════╗
║ ID ║   COUNTRY   ║
╠════╬═════════════╣
║  2 ║ China       ║
║  3 ║ India       ║
║  5 ║ UK          ║
║  7 ║ Philippines ║
╚════╩═════════════╝
于 2013-02-27T07:39:21.877 回答