tags:

views:

505

answers:

4

Hi,

I am getting the following error when trying to run this query in sql 2005:

    SELECT tb.*
    FROM (
     SELECT * 
     FROM vCodesWithPEs INNER JOIN vDeriveAvailabilityFromPE 
     ON vCodesWithPEs.PROD_PERM = vDeriveAvailabilityFromPE.PEID 
     INNER JOIN PE_PDP ON vCodesWithPEs.PROD_PERM = PE_PDP.PEID
    ) AS tb;

Error: The column 'PEID' was specified multiple times for 'tb'.

I am new to sql. Thank You in advance for your advise.

Eneo.

+2  A: 

Looks like you have the column PEID in both tables vDeriveAvailabilityFromPE and *PE_PDP*. The SELECT statement tries to select both, and gives an error about duplicate column name.

MicSim
He does have it in both tables, not only looks like :)
Vinko Vrsalovic
You're right, Vinko. :-)On a sidenote: Why my second table name doesn't get displayed in italics? (put it in *<text>*, but displays as *PE_PDP*) Preview is correct.
MicSim
I don't know, issue for uservoice I think. I tried some of the usual tricks (adding spaces or reformatting) but it didn't work
Vinko Vrsalovic
@MicSim I guess the italic formatting does not like underscore in the name PE_PDP
kristof
+1  A: 

You're joining three tables, and looking at all columns in the output (*).

It looks like the tables have a common column name PEID, which you're going to have to alias as something else.

Solution: don't use * in the subquery, but explicitly select each column you wish to see, aliasing any column name that appears more than once.

Jeremy Smyth
+5  A: 

The problem, as mentioned, is that you are selecting PEID from two tables, the solution is to specify which PEID do you want, for example

 SELECT tb.*
    FROM (
        SELECT tb1.PEID,tb2.col1,tb2.col2,tb3.col3 --, and so on
        FROM vCodesWithPEs as tb1 INNER JOIN vDeriveAvailabilityFromPE as tb2
        ON tb1.PROD_PERM = tb2.PEID 
        INNER JOIN PE_PDP tb3 ON tb1.PROD_PERM = tb3.PEID
    ) AS tb;

That aside, as Chris Lively cleverly points out in a comment the outer SELECT is totally superfluous. The following is totally equivalent to the first.

        SELECT tb1.PEID,tb2.col1,tb2.col2,tb3.col3 --, and so on
        FROM vCodesWithPEs as tb1 INNER JOIN vDeriveAvailabilityFromPE as tb2
        ON tb1.PROD_PERM = tb2.PEID 
        INNER JOIN PE_PDP tb3 ON tb1.PROD_PERM = tb3.PEID

or even

        SELECT * 
        FROM vCodesWithPEs as tb1 INNER JOIN vDeriveAvailabilityFromPE as tb2
        ON tb1.PROD_PERM = tb2.PEID 
        INNER JOIN PE_PDP tb3 ON tb1.PROD_PERM = tb3.PEID

but please avoid using SELECT * whenever possible. It may work while you are doing interactive queries to save typing, but in production code never use it.

Vinko Vrsalovic
A: 

Instead of using * to identify collecting all of the fields, rewrite your query to explicitly name the columns you want. That way there will be no confusion.

Chris Lively