0

我已经搜索过,但可能没有正确表达我的搜索词。我真的可以对以下简单查询使用一些设计帮助。

我有一个列出游戏的父表

GAMENUM     HOMEID     AWAYID
1             25         29
2             12         17
3             13         12

团队表

TEAMID    TEAMNAME
12        Blue 
13        Yellow
17        Red
25        Pink
29        White

我需要的是一个查询来获得一个类似的列表

GAMENUM    HOMEID    AWAYID   HOMETEAM     AWAYTEAM
1          25        29       Pink         White
2          12        17       Blue         Red
3          13        12       Blue

如果没有与 ID 相关联的团队代码,我仍然希望返回游戏记录,但如果找不到,则 HOMETEAM 或 AWAYTEAM 名称为 NULL。

4

1 回答 1

1

试试这个:

SELECT DISTINCT p.GAMENUM, p.HOMEID, p.AWAYID, t1.TEAMNAME [HOMETEAM], t2.TEAMNAME [AWAYTEAM]
FROM [Parent] p
LEFT JOIN Team t1 ON t1.TEAMID = p.HOMEID
LEFT JOIN Team t2 ON t2.TEAMID = p.AWAYID

测试用例:

WITH [Parent] AS (SELECT * FROM (
    SELECT 1 [GAMENUM], 25 [HOMEID], 29 [AWAYID] UNION ALL
    SELECT 2, 12, 17 UNION ALL
    SELECT 3, 13, 12) as [Parent]),

[Team] AS (
    SELECT * FROM (
    SELECT 12 [TEAMID], 'Blue' [TEAMNAME] UNION ALL
    SELECT 13, 'Yellow' UNION ALL
    SELECT 17, 'Red' UNION ALL
    SELECT 25, 'Pink' UNION ALL
    SELECT 29, 'White') as [Team])

SELECT p.GAMENUM, p.HOMEID, p.AWAYID, t1.TEAMNAME [HOMETEAM], t2.TEAMNAME [AWAYTEAM]
FROM [Parent] p
LEFT JOIN Team t1 ON t1.TEAMID = p.HOMEID
LEFT JOIN Team t2 ON t2.TEAMID = p.AWAYID

请检查SQL Fiddle以获取测试用例结果

于 2013-03-13T20:21:46.580 回答