简体   繁体   中英

Selecting ambiguous column from subquery

Suppose we have the following query:

       select c.a, c.b, c.d
        from
           (select * from 
             tab1 join tab2
             on tab1.id = tab2.id)c

I get the following error: ERROR: 42702: column reference "d" is ambiguous

How would I fix this? Can I do something like c.tab1.id ?

You may write your query like:

SELECT a, b, d FROM (SELECT tab1.a AS a, tab1.b AS b, tab2.c AS c, tab2.d AS d
FROM tab1 JOIN tab2 ON tab1.id = tab2.id)c;

The error is happening because both tab1 and tab2 have a column called d .

The simplest solution is to eliminate the subquery:

select ?.a, ?.b, ?.d
from tab1 join
     tab2
     on tab1.id = tab2.id

The ? is a placeholder for the table where the column comes from.

If you need the subquery, then you should similarly use qualified column names instead of select * , so you identify where the columns are coming from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM