简体   繁体   English

在 SQL Server 中选择唯一的列

[英]Selecting unique columns in SQL Server

(I wish to get a solution compatible with SQL Server) (我希望得到一个与 SQL Server 兼容的解决方案)

Let's say I have a table 'x' with the columns {A,B,C,D,E} and another table 'y' with the columns {A,B,C,F,G}.假设我有一个包含 {A,B,C,D,E} 列的表“x”和另一个包含 {A,B,C,F,G} 列的表“y”。

I now execute the following query:我现在执行以下查询:

SELECT * FROM(
(SELECT * FROM x) AS M
LEFT JOIN
(SELECT * FROM y) AS N
ON M.A=N.A AND M.B=N.B AND M.C=N.C) AS K

The output table has the columns {A,B,C,D,E,A,B,C,F,G} while I actually wish to select a table with the columns {A,B,C,D,E,F,G}输出表有 {A,B,C,D,E,A,B,C,F,G} 列,而我实际上希望选择一个包含 {A,B,C,D,E,F 列的表,G}

Is there any way around this problem?有没有办法解决这个问题?

You may use a simpler left join and specify the columns you wish to select:您可以使用更简单的左连接并指定要选择的列:

SELECT
    m.A,
    m.B,
    m.C,
    m.D,
    m.E,
    n.F,
    n.G
FROM x AS m
LEFT JOIN y AS n
    ON m.A = n.A AND m.B = n.B AND m.C = n.C;

You don't really need all the subqueries here as far as I can tell.据我所知,您并不真正需要这里的所有子查询。 Also, in general doing SELECT * is not a good thing, and you should always explicitly list out the columns you wish to select.此外,通常执行SELECT *不是一件好事,您应该始终明确列出您希望选择的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM