交叉联接2选择语句(SQL)

时间:2019-10-03 20:01:00

标签: sql

我想交叉连接两个选择语句。设置表格代码:

CREATE TABLE [Table1] ([Letter] nvarchar(10), [Number] int)

INSERT INTO [Table1] VALUES ('A', 1)
INSERT INTO [Table1] VALUES ('A', 2)
INSERT INTO [Table1] VALUES ('B', 1)
INSERT INTO [Table1] VALUES ('B', 4)
INSERT INTO [Table1] VALUES ('C', 10)

CREATE TABLE [Table2] ([Team] nvarchar(10), [League] nvarchar(10), [Player] nvarchar(10))

INSERT INTO [Table2] VALUES ('Cubs', 'NL', 'Kevin')
INSERT INTO [Table2] VALUES ('Cubs', 'NL', 'Steve')
INSERT INTO [Table2] VALUES ('Yankees', 'AL', 'Steve')
INSERT INTO [Table2] VALUES ('Red Sox', 'AL', 'Carl')
INSERT INTO [Table2] VALUES ('Dodgers', 'NL', 'Tony')

尝试输入的代码:

SELECT DISTINCT [Letter] FROM [Table1]
CROSS JOIN
SELECT DISTINCT [Team], [League] FROM [Table2]

所需的输出:

Name  |  Team  |  League

A | Cubs | NL
A | Yankees | AL
A | Red Sox | AL
A | Dodgers | NL
B | Cubs | NL
B | Yankees | AL
B | Red Sox | AL
B | Dodgers | NL
C | Cubs | NL
C | Yankees | AL
C | Red Sox | AL
C | Dodgers | NL

谢谢。 (如果最终结果是所需的输出,但与我的排序不同,那完全可以)

2 个答案:

答案 0 :(得分:1)

您的想法很好,但是CROSS JOIN子句仅在FROM子句中可以理解:

SELECT l.Letter, tl.Team, tl.League
FROM (SELECT DISTINCT [Letter] FROM [Table1]) l CROSS JOIN
     (SELECT DISTINCT [Team], [League] FROM [Table2]) tl;

答案 1 :(得分:1)

修改后的代码:

select * from
(SELECT DISTINCT [Letter] FROM [Table1]) a
CROSS JOIN
(SELECT DISTINCT [Team], [League] FROM [Table2]) b

加入并不像工会那样起作用,尽管我可以看到您可能对为什么感到困惑!