postgresql 查询连接表

uemypmqf  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(191)

我正在尝试inner join两个表。第一个表可以有两个记录,因此对它执行group by。错误:
列“b.db”必须出现在GROUP BY子句中或在聚合函数中使用

select distinct a.schemaname,a.tablename,max(a.tbl_cmmt_txt) as 
tbl_cmmt_txt,max(a.cleansed_tbl_cmmt_txt) as cleansed_tbl_cmmt_txt,max(a.tbl_dscr_txt) 
as tbl_dscr_txt,max(a.cleansed_tbl_dscr_txt)as cleansed_tbl_dscr_txt,max(a.tbl_annt_txt) 
as tbl_annt_txt,max(a.cleansed_tbl_annt_txt) as cleansed_tbl_annt_txt,max(a.dw_etl_sess_nm),max(a.dw_ld_grp_val),max(a.dw_ins_dts),max(a.dw_upd_dts)
,b.db,b.schemaname,b.tablename,b.tabledescription,b.table_id,b.ts_updated,b.user_name
 from test.sample a INNER JOIN  test.sample1 b
 ON
 lower(a.schemaname)=lower(b.schemaname)
 AND lower(a.tablename)=lower(b.tablename)
 where a.schemaname is not null
 group by a.schemaname,a.tablename
li9yvcax

li9yvcax1#

先聚合,后加入:

SELECT a.*
     , b.db, b.schemaname, b.tablename, b.tabledescription, b.table_id, b.ts_updated, b.user_name
FROM  (
   SELECT schemaname, tablename
        , max(tbl_cmmt_txt) AS tbl_cmmt_txt, max(cleansed_tbl_cmmt_txt) AS cleansed_tbl_cmmt_txt, ...  -- more
   FROM   test.sample a
   WHERE  schemaname IS NOT NULL
   GROUP  BY schemaname, tablename
   ) a
JOIN   test.sample1 b ON lower(a.schemaname) = lower(b.schemaname)
                     AND lower(a.tablename) = lower(b.tablename);

参见:

  • 单个查询中的多个array_agg()调用

我是凭直觉删除了DISTINCT。目前还不清楚表sample1是否可以保存重复的匹配项,以及在这种情况下需要选择什么。
你可能想要LEFT JOIN,这取决于你的未公开目标。
此外,lower(tablename)lower(schemaname)也是可疑的。当使用双引号时,Postgres标识符区分大小写。参见:

  • PostgreSQL列名区分大小写吗?

而且,你在schemaname ...上聚合,但在lower(schemaname) ...上加入。通常情况下,你会希望两者都一样。

相关问题