为什么postgresql查询中创建的中间关系不能在where子句筛选器中引用?

为什么postgresql查询中创建的中间关系不能在where子句筛选器中引用?,sql,postgresql,subquery,sql-delete,Sql,Postgresql,Subquery,Sql Delete,我正在尝试从postgres中的表中删除重复数据。在我的表中,没有主键 postgres=# select * from customer_temp; id | firstname | country | phonenumber ----+-----------+-----------+------------- 1 | Sachin | India | 3454 2 | Viru | India | 3454 3 |

我正在尝试从postgres中的表中删除重复数据。在我的表中,没有主键

postgres=# select * from customer_temp;
 id | firstname |  country  | phonenumber
----+-----------+-----------+-------------
  1 | Sachin    | India     |        3454
  2 | Viru      | India     |        3454
  3 | Saurav    | India     |        3454
  4 | Ponting   | Australia |        3454
  5 | Warne     | Australia |        3454
  7 | Be;;      | England   |        3454
  8 | Cook      | England   |        3454
  8 | Cook      | England   |        3454
  8 | Cook      | England   |        3454
(9 rows)
我正在使用以下查询删除重复记录

delete from customer_temp temp 
using (select  out1.id, out1.firstname 
       from customer_temp out1 
       where (select count(out2.id) 
              from customer_temp out2 
              where out1.firstname=out2.firstname group by out2.firstname
              ) > 1
       ) temp1 
where temp.id in (select id 
                  from temp1 
                  where id not in(select id 
                                  from temp1 
                                  LIMIT 1 OFFSET 0));
但我得到了以下错误:-

错误:关系temp1不存在 第1行:…名称>1 temp1,其中temp1中的temp.id从temp1中选择id wher。。。 虽然关系temp1是作为using的一部分创建的,但是为什么我不能在where子句过滤器中使用它们呢

根据,首先执行FROM,行的结果可用于查询执行的下一个阶段。那么,为什么temp1不能用于where部分的子查询。

Hmmm。假设id唯一标识每一行,这是写入逻辑的简单方法:

delete from customer_temp
    where id not in (select min(ct2.id)
                     from customer_temp ct2
                     where ct2.id is not null
                     group by ct2.firstname, ct2.country, ct2.phonenumber
                    );
我注意到我在子查询中使用not in。我通常会提醒大家不要这样做,虽然这是安全的,因为在哪里。您可以使用exists或使用>和相关子查询执行类似的操作

编辑:

若id不是唯一的,那个么对于一个列来说,它是一个非常糟糕的名称。但除此之外,您还可以使用oid:

但是,最好的方法可能只是重建表:

create table customer_temp_temp as
    select distinct on (firstname, country, phone_number) t.*
    from customer_temp t
    order by firstname, country, phone_number;

也许开始格式化您的源代码。若表并没有主键,会发生什么?在这种情况下,查询是否会更改?
create table customer_temp_temp as
    select distinct on (firstname, country, phone_number) t.*
    from customer_temp t
    order by firstname, country, phone_number;