SQL内连接查询返回两个相同的列
假设我有以下 SQL 查询:
SELECT *
FROM employee
INNER JOIN department ON employee.EmpID = department.EmpID
我想问一下,为什么我会得到两个 EmpID
列,以及如何才能只得到其中一个列,最好是第一个列。
我正在使用 SQL 服务器
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
精确地指定您需要哪些列,而不是使用星号来选择所有列。
Be precise and specify which columns you need instead of using the astrisk to select all columns.
您从这两个表中获取所有列,这就是为什么您有两个
EmpID
列。删除公共列的唯一JOIN
类型是NATURAL JOIN
,它不是由 SQL Server 实现的。您的查询将如下所示:这通过比较两个表中具有相同名称的所有列来生成连接谓词。生成的表仅包含每对同名列的一列。
You get all columns from these two tables, that's why you have two
EmpID
columns. The onlyJOIN
type that removes common column isNATURAL JOIN
, which is not implemented by SQL Server. Your query would look then like this: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.
由于您要求查询,因此您将从查询中涉及的所有表中获取所有列:
SELECT *
如果您只需要特定列- 您需要指定您想要哪些:
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:
不要使用
*
。在字段列表中指定所需的列。Don't use
*
. Specify the columns you want in the field list.正如其他人所述,不要使用
*
请参阅此问题了解原因:
哪个更快/最好? SELECT * 或 SELECT column1、colum2、column3 等
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
本质上,您的问题的答案是 SQL
SELECT
查询的输出不是关系,因此,如果您不小心,您可能会得到重复的属性名称(列)和行。标准 SQL 有一些结构可以缓解 SQL 的非关系问题,例如
NATURAL JOIN< /code>
将确保结果只有一个
EmpID
属性。遗憾的是,SQL Server 不支持此语法,但您可以投票支持它 此处。因此,您被迫以手写形式写出所需的列,并使用表名来限定您喜欢的属性,例如
employee.EmpID
。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 oneEmpID
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
.