1

问题与此类似如何编写一个 MySQL 查询,该查询返回一个临时列,其中包含与该行相关的项目是否存在于另一个表中的标志

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

我有两个表:'competitions' 和 'competition_entries'

比赛:

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 的条目

4

1 回答 1

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
于 2012-10-11T22:19:09.153 回答