1

是否可以在 TD 的 case 语句中以某种方式使用 select 子句(而不是进行连接)?

我想做这样的事情:

SELECT 
   id, 
   , count(*)
   , (CASE WHEN id IN ANY (SELECT DISTINCT ID FROM PARTICIPANTS_TABLE)                             
        THEN 1 ELSE 0 
      end) AS participant 
FROM EVERYONE_TABLE
GROUP BY id

我得到的错误是“CASE 表达式的 WHEN 子句中的非法表达式”。

4

2 回答 2

5

您应该将 SELECT 更改为标量子查询

SELECT 
   id 
   , COUNT(*)
   , (CASE WHEN id = (SELECT MIN(ID) FROM PARTICIPANTS_TABLE AS p
                      WHERE p.id = e.id)
        THEN 1 ELSE 0 
      END) AS participant 
FROM EVERYONE_TABLE AS e
GROUP BY id

但我始终遵循的一个基本规则是避免选择列表中的标量子查询,根据我的经验,它们的优化往往很糟糕。

我会将其重写为外部联接(恕我直言,这是人们编写标量子查询的主要原因,在大多数情况下,他们只是隐藏了外部联接):

SELECT 
   t1.id 
   , COUNT(*)
   , COUNT(t2.ID) AS participant 
FROM EVERYONE_TABLE AS t1
LEFT JOIN
  (SELECT DISTINCT ID FROM PARTICIPANTS_TABLE) AS t2
ON t1.id = t2.id
GROUP BY t1.id

另外,这种语法更容易理解,至少对我来说:-)

于 2013-09-11T08:30:42.443 回答
0

是的,这应该使用正确的语法:

SELECT id,
       (CASE WHEN id IN (SELECT DISTINCT ID FROM PARTICIPANTS_TABLE) 
             THEN 1 ELSE 0
         end) AS participant;

但是,这distinct是不必要的:

SELECT id,
       (CASE WHEN id IN (SELECT ID FROM PARTICIPANTS_TABLE) 
             THEN 1 ELSE 0
         end) AS participant;
于 2013-09-11T02:31:40.677 回答