我有两张桌子:
all_countries
╔════╦═════════════╗
║ ID ║ COUNTRY ║
╠════╬═════════════╣
║ 1 ║ USA ║
║ 2 ║ China ║
║ 3 ║ India ║
║ 4 ║ France ║
║ 5 ║ UK ║
║ 6 ║ Australia ║
║ 7 ║ Philippines ║
╚════╩═════════════╝
supported_countries
╔════════════╦═══════════╦═══════════╗
║ 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;
如果filter = 2,应该是我想得到这个结果。
╔════╦═════════════╗
║ ID ║ COUNTRY ║
╠════╬═════════════╣
║ 2 ║ China ║
║ 3 ║ India ║
║ 5 ║ UK ║
║ 7 ║ Philippines ║
╚════╩═════════════╝
我正在进行正确的查询吗?
答案 0 :(得分: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 ║
╚════╩═════════════╝