简体   繁体   中英

Selecting unique columns in SQL Server

(I wish to get a solution compatible with 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}.

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}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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