SQL inner join query returns two identical columns
Let's say I have the following SQL query:
SELECT *
FROM employee
INNER JOIN departm开发者_如何学Pythonent 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
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.
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.
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
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
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
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
.
精彩评论