Search code examples
postgresqlpostgiscommon-table-expression

Is there a way to alias a query of the type "table.column" inside a function?


I created a CTE, the second part of the CTE contains a select with a st_contains. In this one, i've two columns of diferent tables with the same name. I want to alias one of this 'table.column' combination becouse when I do the selection at the end of the CTE outputs an error; column reference " " is ambiguous.

with
   table1 as (
   ...
   ),         
   table2 as (
   select*
      from table3, table4
      where st_contains (table3.atribute1, table4.atribute1)
)
select
   table1.atribute1      
   table2.atribute1      #here i need somethig like table2.table3.atribute1
   from table1
   join table2 on table1.atribute2=table2.atribute2
;

I hope i explined the problem well. Thanks!


Solution

  • Alias the table3 and table4 columns in your table2 CTE to resolve the ambiguity.

    with
       table1 as (
       ...
       ),         
       table2 as (
       select table3.attribute1 table3atrr1, table4.attribute1 table4attr1
          from table3, table4
          where st_contains (table3.atribute1, table4.atribute1)
    )
    select
       table1.atribute1      
       table2.table3atrr1 -- use the aliased column name
       from table1
       join table2 on table1.atribute2=table2.atribute2
    ;