根据另一个表中的特定行是否存在来选择列

时间:2012-10-11 22:17:03

标签: sql-server tsql

问题类似于How to write a MySQL query that returns a temporary column containing flags for whether or not an item related to that row exists in another table

除了我需要更具体地说明哪些行存在

我有两张桌子:'竞赛'和'竞赛条目'

比赛项目:

ID    | NAME      | TYPE
--------------------------------
1     | Example   | example type
2     | Another   | example type

比赛参赛作品

ID    | USERID    | COMPETITIONID
---------------------------------
1     | 100       | 1
2     | 110       | 1
3     | 110       | 2
4     | 120       | 1

我想选择比赛,但添加一个额外的栏目,指明用户是否参加过比赛。这是我当前的SELECT语句

SELECT
    c.[ID],
    c.[NAME],
    c.[TYPE],
    (CASE 
        WHEN e.ID IS NOT NULL AND e.USERID = @userid THEN 1 
        ELSE 0 
        END
    ) AS 'ENTERED'      

FROM competitions AS c
LEFT OUTER JOIN competition_entries AS e
ON e.COMPETITIONID = c.ID

@userid参数设置为110所需的结果集是

ID    | NAME    | TYPE         | ENTERED
-------------------------------------
1     | Example | example type | 1
2     | Another | example type | 1

但我得到了这个

ID    | NAME    | TYPE         | ENTERED
-------------------------------------
1     | Example | example type | 0
1     | Example | example type | 1
1     | Example | example type | 0
2     | Another | example type | 1  

因为它正在计算所有用户ID的条目

1 个答案:

答案 0 :(得分:3)

修复您的查询

SELECT
    c.[ID],
    c.[NAME],
    c.[TYPE],
    MAX(CASE 
        WHEN e.ID IS NOT NULL AND e.USERID = @userid THEN 1 
        ELSE 0 
        END
    ) AS 'ENTERED'      
FROM competitions AS c
LEFT OUTER JOIN competition_entries AS e ON e.COMPETITIONID = c.ID
GROUP BY
    c.[ID],
    c.[NAME],
    c.[TYPE]

另一种方法是使用EXISTS重写它,它几乎相同,但可能更容易理解 顺便说一句,不推荐使用列名上的单引号。使用方括号。

SELECT
    c.[ID],
    c.[NAME],
    c.[TYPE],
    CASE WHEN EXISTS (
        SELECT *
        FROM competition_entries AS e
        WHERE e.COMPETITIONID = c.ID
          AND e.USERID = @userid) THEN 1 ELSE 0 END [ENTERED]
FROM competitions AS c