SQL inner join query returns two identical columns

雨燕双飞 提交于 2019-12-13 15:14:44

问题


Let's say I have the following SQL query:

SELECT *
FROM employee 
INNER JOIN department ON employee.EmpID = department.EmpID

I wanted to ask, why I am getting two EmpID columns, and how can I get only one of those, preferably the first.

I'm using SQL server


回答1:


SELECT employee.EmpID, employee.name, ...
FROM employee 
INNER JOIN department ON employee.EmpID=department.EmpID

Be precise and specify which columns you need instead of using the astrisk to select all columns.




回答2:


You get all columns from these two tables, that's why you have two EmpID columns. The only JOIN type that removes common column is NATURAL JOIN, which is not implemented by SQL Server. Your query would look then like this:

SELECT *
FROM employee 
NATURAL JOIN department

This generates join predicates by comparing all columns with the same name in both tables. The resulting table contains only one column for each pair of equally named columns.




回答3:


You're getting all columns from all tables involved in your query since you're asking for it: SELECT *

If you want only specific column - you need to specify which ones you want:

SELECT e.EmpID, e.Name as 'Employee Name', d.Name AS 'Department Name'
FROM employee e 
INNER JOIN department d ON e.EmpID = d.EmpID



回答4:


Don't use *. Specify the columns you want in the field list.

SELECT E.EmpID, E.EmpName -- etc 
FROM employee as E
  INNER JOIN department as D
    ON E.EmpID=D.EmpID



回答5:


As stated by others, don't use *

See this SO question for reasons why:

Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc




回答6:


Essentially, the answer to your question is that the output from a SQL SELECT query is not a relation, and therefore if you do not take care you may end up with duplicate attribute names (columns) and rows.

Standard SQL has some constructs to mitigate SQL's non-relational problems e.g. NATURAL JOIN would ensure the result has only one EmpID attribute. Sadly, SQL Server does not support this syntax but you can vote for it here.

Therefore, you are forced to write out in long-hand the columns you want, using the table name to qualify which attribute you prefer e.g. employee.EmpID.



来源:https://stackoverflow.com/questions/7157891/sql-inner-join-query-returns-two-identical-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!