0

I've searched a lot but I still don't get it.

Here's my sample code

SELECT sp.testno, sp.companyid, st.* 
FROM sponsor AS sp
LEFT JOIN
(
    SELECT a.sponsorempno, (CASE WHEN t.companyid IS NULL OR t.companyid = '' THEN'aa' ELSE t.companyid END) agncy, a.controlno, a.tnpl, t.* 
    FROM applicant AS a
    LEFT JOIN
        test AS t
    ON a.controlno = t.controlno 
) AS st
ON sp.testno = st.testno

I still returns an error:

#1060 - Duplicate column name 'controlno'

Can somebody tell me what's wrong with the code?

3
  • The code (=question) lacks sample data, and DDL for the tables involved. Commented Nov 18, 2020 at 7:23
  • 1
    You get two columns with the same name from different tables - a.controlno explicitly and t.controlno implicitly from t.*. Assign an alias to at least one of columns (for example, ... , a.controlno AS a_controlno, ...). Or replace ON a.controlno = t.controlno with USING (controlno) - these columns will be collapsed into one with the value taken from left table (a.controlno). Commented Nov 18, 2020 at 7:25
  • Already answered here: stackoverflow.com/questions/9260936/… Commented Nov 18, 2020 at 7:26

1 Answer 1

1

In the subselect of your join, you are selecting a.controlno and by t.* t.controlno. You should provide an alias for one of the selected columns. In your case a.controlno. This is necessary, because the table aliases of the inner select are lost, when accessing it from the outer one.

The statement below should work, if there aren't any other duplicate column names in test and the set of used columns from applicant.

SELECT sp.testno, sp.companyid, st.* 
FROM sponsor AS sp
LEFT JOIN
(
    SELECT a.sponsorempno, (CASE WHENt.companyid IS NULL OR t.companyid = '' THEN'aa' ELSE t.companyid END) agncy, a.controlno as a_controlno, a.tnpl, t.* 
    FROM applicant AS a
    LEFT JOIN
        test AS t
    ON a.controlno = t.controlno 
) AS st
ON sp.testno = st.testno
Sign up to request clarification or add additional context in comments.

1 Comment

it worked! thanks for this! now I understand better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.