如何在没有PK的情况下组合2个或更多表

时间:2013-05-15 12:35:26

标签: sql sql-server

我一直试图使用UNIONS和JOINS 4表合并而没有成功。 每个表只有一列和两行,它们没有任何共同之处。我正在尝试创建一个表,它将所有行与所有行组合在一起。

Example:
Table 1
vegetables
Potato  
Tomato 

Table 2
Utilities
Knife
Pan

Table 3
Fruits
Orange
Apple

Table 4
Liquids
Wine
Water

Final Table:

vegetables  Utilities  Fruits   Liquids
Potato      Knife      Orange   wine 
Tomato      Pan        Apple    Water

很抱歉这些奇怪的名字,如果这已经被问到了。 我尝试了几个我发现的例子,但大多数都使用公共密钥进行过滤,但由于表没有任何内容当我尝试这个例子时,我最终得到了一个包含8行的表 这些表也可以从1到10的行数变化,但如果有10个,它们都会变化。

提前致谢。

编辑:我正在使用SQL Server Express 2012

1 个答案:

答案 0 :(得分:3)

试试这个 -

查询1:

DECLARE @temp1 TABLE (vegetables NVARCHAR(50))
INSERT INTO @temp1 (vegetables)
VALUES ('Potato'), ('Tomato')

DECLARE @temp2 TABLE (Utilities NVARCHAR(50))
INSERT INTO @temp2 (Utilities)
VALUES ('Knife'), ('Pan')

DECLARE @temp4 TABLE (Liquids NVARCHAR(50))
INSERT INTO @temp4 (Liquids)
VALUES ('Wine'), ('Water')

DECLARE @temp3 TABLE (Fruits NVARCHAR(50))
INSERT INTO @temp3 (Fruits)
VALUES ('Orange'), ('Apple')

SELECT t1.vegetables, t2.Utilities, t3.Fruits, t4.Liquids
FROM (
    SELECT t.vegetables, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp1 t
) t1
JOIN (
    SELECT t.Utilities, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp2 t
) t2 ON t1.id = t2.id
JOIN (
    SELECT t.Fruits, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp3 t
) t3 ON t1.id = t3.id
JOIN (
    SELECT t.Liquids, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp4 t
) t4 ON t1.id = t4.id

输出1:

vegetables  Utilities  Fruits   Liquids
----------- ---------- -------- ---------
Potato      Knife      Wine     Orange
Tomato      Pan        Water    Apple    

查询2 (您可能的答案评论)

SELECT t1.vegetables, t2.Utilities, t3.Fruits, t4.Liquids
FROM @temp1 t1
CROSS JOIN @temp2 t2
CROSS JOIN @temp3 t3
CROSS JOIN @temp4 t4

输出2:

vegetables   Utilities  Fruits    Liquids
------------ ---------- --------- -------
Potato       Knife      Wine      Orange
Potato       Knife      Apple     Orange
Potato       Knife      Wine      Water
Potato       Knife      Apple     Water
Tomato       Knife      Wine      Orange
Tomato       Knife      Apple     Orange
Tomato       Knife      Wine      Water
Tomato       Knife      Apple     Water
Potato       Pan        Wine      Orange
Potato       Pan        Apple     Orange
Potato       Pan        Wine      Water
Potato       Pan        Apple     Water
Tomato       Pan        Wine      Orange
Tomato       Pan        Apple     Orange
Tomato       Pan        Wine      Water
Tomato       Pan        Apple     Water