sql - PostgreSQL 选择加入不在列表中

标签 sql postgresql join

项目使用Postgres 9.3

我有如下表格(已简化):

t_person (30 million records)
- id
- first_name
- last_name
- gender

t_city (70,000 records)
- id
- name
- country_id

t_country (20 records)
- id
- name

t_last_city_visited (over 200 million records)
- person_id
- city_id
- country_id
  - There is a unique constraint on person_id, country_id to
    ensure that each person only has one last city per country

我需要做的是以下变化:

获取访问过“英国”国家/地区的女性的 ID 但从未访问过国家“美国”

我试过下面的,但是太慢了。

select t_person.id from t_person
join t_last_city_visited
  on (
          t_last_city_visited.person_id = t_person.id
          and country_id = (select id from t_country where name = 'UK')
     )
where gender = 'female'
except
(
    select t_person.id from t_person
    join t_last_city_visited
      on (
             t_last_city_visited.person_id = t_person.id
             and country_id = (select id from t_country where name = 'USA')
         )
)

如果有任何帮助,我将不胜感激。

最佳答案

提示:您想在这里做的是找到曾经访问过英国但没有访问过美国的女性。

类似于:

select ...
from   t_person
where  ...
   and exists (select null
                 from t_last_city_visited join
                      t_country on (...)
                where t_country.name = 'UK')
   and not exists (select null
                 from t_last_city_visited join
                      t_country on (...)
                where t_country.name = 'US')

另一种方法,找到访问过英国而不是美国的人,然后您可以将其加入到人中以按性别过滤:

select   person_id
  from   t_last_city_visited join
         t_country on t_last_city_visited.country_id = t_country.id
 where   t_country.name in ('US','UK')
group by person_id
having   max(t_country.name) = 'UK'

关于sql - PostgreSQL 选择加入不在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338670/

相关文章:

sql - 当记录数达到一定值时,备注字段显示汉字或符号而不是实际值

postgresql - Docker-Compose 和 Postgres 扩展

mysql - 可以跨表索引吗?

scala - Spark : How to join two `Dataset` s A and B with the condition that an ID array column of A does NOT contain the ID column of B?

sql - 棘手的删除。我如何能?

mysql - 更改时区phpmyadmin?

linux - 如何升级 pg_dumpall

java - Spark-Java : Display join RDD

mysql - 与 child 取得时差

sql - pgbench 处理大量事务后数据库暂时断开连接