How to fix an “ambigous column name error using inner join” error

后端 未结 3 655
深忆病人
深忆病人 2021-01-25 06:56

I am taking a query from a database, using two tables and am getting the error described in the title of my question. In some cases, the field I need to query by is in table A,

3条回答
  •  情话喂你
    2021-01-25 07:18

    Employee
    ------------------
    Emp_ID  Emp_Name    Emp_DOB Emp_Hire_Date   Emp_Supervisor_ID
    
    
    Sales_Data
    ------------------
    Check_ID    Tender_Amt  Closed_DateTime Emp_ID
    

    Every column you reference should be proceeded by the table alias (but you already knew that.) For instance;

    SELECT E.Emp_ID, B.Check_ID, B.Closed_DateTime
    FROM Employee E 
        INNER JOIN Sales_Data SD ON E.Emp_ID = SD.Emp_ID
    

    However, when you select all (*) it tries to get all columns from both tables. Let's see what that would look like:

    SELECT *
    FROM Employee E 
        INNER JOIN Sales_Data SD ON E.Emp_ID = SD.Emp_ID
    

    The compiler sees this as:

    **Emp_ID**, Emp_Name, Emp_DOB, Emp_Hire_Date, Emp_Supervisor_ID, 
    Check_ID, Tender_Amt, Closed_DateTime, **Emp_ID**
    

    Since it tries to get all columns from both tables Emp_ID is duplicated, but SQL doesn't know which Emp_ID comes from which table, so you get the "ambiguous column name error using inner join".

    So, you can't use (*) because whatever column names that exist in both tables will be ambiguous. Odds are you don't want all columns anyway.

    In addition, if you are adding any columns to your SELECT line via your cfloop they must be proceed by the table alias as well.

    --Edit: I cleaned up the examples and changed "SELECT * pulls all columns from the first table" to "SELECT * pulls all columns from both tables". Shawn pointed out I was incorrect.

提交回复
热议问题