2016-07-25 51 views
0
apps: 
id  name 
--  -------- 
1  Facebook 
2  Twitter 
3  Pokemon 


markets: 
id  app_id code 
--  ------ ---- 
1  1   US 
2  1   CA 
3  3   CA 

下面的查询将获得美国应用:如何编写SQL查询以获取记录(如果匹配或第二个表中没有匹配)?

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

回答

2

这里有一个选项与outer join

select * 
from apps 
    left join markets 
     on markets.app_id = apps.id 
where markets.app_id is null or 
    markets.code = 'US' 
+0

它的工作原理。 'markets.id为null'是否等价? –

+0

@BSeven - 是的,它是相同的。关键是从'markets'表中进行'null'检查,而不管被检查的字段。 – sgeddes

1

作为一个说明,你不要似乎想要关于应用程序的信息,所以你可以这样做:

select a.* 
from apps a 
where not exists (select 1 from markets m where m.app_id = a.id) or 
     exists (select 1 from markets m where m.app_id = a.id and m.code = 'US'); 
相关问题