为什么这个联盟没有给我两列?

时间:2016-11-25 18:59:05

标签: sql-server

我想在连接的输出中有两列。我只得到一个,即storeID。 StoreComponentID不在那里。

Here are the two tables, the query, and the results of the query

2 个答案:

答案 0 :(得分:3)

如果你想要两列你需要声明两列

SELECT column1, NULL as column2 -- even when Table1 doesnt have column2
FROM Table1
UNION 
SELECT NULL as column1, column2 -- even when Table2 doesnt have column1
FROM Table2

现在,如果你想并排进行某种合并。

WITH idA as (
     SELECT StoreComponentID,
            ROW_NUMBER() OVER (ORDER BY StoreComponentID) as rn
     FROM StoreComponent
), idB as (
     SELECT StoreID
            ROW_NUMBER() OVER (ORDER BY StoreID) as rn
     FROM Store
)
SELECT idA.StoreComponentID, 
       idB.StoreID
FROM idA 
FULL JOIN idB
  ON idA.rn = idB.rn

答案 1 :(得分:0)

我找到了一个简单的解决方案:

select S.storeid as sID, SC.storecomponentid as SCID from tstore as S, tstorecomponent as SC

The results I wanted