有人知道如何在Postgresql中执行这种查询吗?

SELECT * 
FROM tabA 
WHERE NOT EXISTS (
    SELECT * 
    FROM tabB 
    WHERE tabB.id = tabA.id
)

当我执行这样的查询时,postgresql会抱怨"ERROR: Greenplum Database does not yet support that query"

编辑:这个怎么样

SELECT * 
FROM tabA 
WHERE NOT EXISTS (
    SELECT * 
    FROM tabB WHERE tabB.id = tabA.id AND tabB.id2 = tabA.id2
)

EDIT:
I tested in postgresql 8.2.15 for the 4 answers provided by @ypercube. Conclusions are:

1) The first does not work in this version of postgresql, as I said above in the question. The error message can be found there too.

2) For the other three answers, the execution speed is: (3)LEFT JOIN > (4)EXCEPT >> (2)NOT IN.
Specifically, for queries that have the same syntax, (3)LEFT JOIN takes about 5580ms, (4)EXCEPT takes about 13502ms, and (2)NOT IN takes more than 100000 (In fact I did not wait util it finished).
Is there any particular reasons for NOT IN clause to be so slow?
Cheng

推荐答案

有3种(主要)方法可以进行此类查询:

  1. NOT EXISTS相关子查询

  2. NOT IN子查询

  3. LEFT JOINIS NULL支票:

你发现第一种方法在Greenplum中确实有效@Marco和@juergen提供了第二条路.这是第三个,它可能会绕过Greenplum的限制:

SELECT tabA.* 
FROM 
    tabA 
  LEFT JOIN 
    tabB 
      ON  tabB.id = tabA.id 
      AND tabB.id2 = tabA.id2
WHERE tabB.id IS NULL ;

这(第四种方式)也适用于Postgres(支持EXCEPT名操作员):

SELECT a.*
FROM a
WHERE id IN
      ( SELECT id
        FROM a
      EXCEPT
        SELECT id
        FROM b
      ) ; 

SQL-Fiddle人测试(所有4人都在研究生阶段).

Postgresql相关问答推荐

从子查询中的排序结果中获取前X行

Postgres 13.8 -如何在对数据执行窗口操作时返回所有行

无法在kubernetes中设置postgres复制

supabase 中的交易

ST_Intersects 太慢

AWS RDS Postgres 性能缓慢的数据传输

如何计算过滤器中的百分比

如何在 PostgreSQL hstore 中使用通配符查询值

PostgreSQL:在timestamp::DATE 上创建索引

UPDATE implies move across partitions

需要将整个 postgreSQL 数据库加载到 RAM 中

什么是 postgres 超级用户

使用 postgres regexp_replace 将字符串列表替换为始终相同的字符串

如果 PostgreSQL 数据库中存在,则删除表

如何在 Postgresql 中正确使用 FETCH FIRST?

Postgresql:在插入列时(或之前)自动小写文本

每个数据库提供程序类型允许的最大参数数是多少?

Rails PG::UndefinedTable:错误:missing FROM-clause entry for table

使用 Postgres 在 Rust 的 Diesel 库中添加时间戳

如何获取一个月的天数?