apps:
id name
-- --------
1 Facebook
2 Twitter
3 Pokemon
markets:
id app_id code
-- ------ ----
1 1 US
2 1 CA
3 3 CA
以下查询将获取适用于美国的应用:
SELECT *
FROM apps
INNER JOIN markets
ON markets.app_id = apps.id
AND markets.code = 'US'
但是如何获取上述记录,加上任何没有市场的应用?
查询将返回应用 1 和 2。
PostgreSQL 9.3.5、9.3.9 和 9.4.7
最佳答案
这是一个带有外连接
的选项:
select *
from apps
left join markets
on markets.app_id = apps.id
where markets.app_id is null or
markets.code = 'US'
关于sql - 如果第二个表中有匹配项或没有匹配项,如何编写 SQL 查询来获取记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38579089/