在where子句中使用带有CASE的别名列名

时间:2014-09-30 06:30:40

标签: mysql sql

如何修复此查询?我收到以下错误:

  

未知栏' count_of_confirmed_rec'在' where子句'

MySQL查询:

SELECT 
(SELECT COUNT(a.col_1)FROM table_1 a
JOIN table 2 b ON a.col_id= b.col_id) count_of_confirmed_rec,
c.col_1,
FROM table_3 c
LEFT JOIN table_4 d ON c.col_id = d.col_id 
WHERE d.col_1 = 'value'
AND c.col_1 = CASE count_of_confirmed_rec
WHEN 0 THEN 0 ELSE 1 END

1 个答案:

答案 0 :(得分:1)

首先,用于计算count_of_confirmed_rec的子查询与外部查询无关;因此,它将为查询的所有返回行提供相同的值。不确定这是否是你想要的。

其次,您的条件d.col_1 = 'value'看起来也可能是错误的左连接。

为了在where语句中测试count_of_confirmed_rec的值,您需要将除WHERE语句之外的所有内容放在子查询中,并对查询返回的行应用条件(未经测试):

select count_of_confirmed_rec, c_col_1 from (
SELECT (SELECT COUNT(a.col_1)FROM table_1 a JOIN table 2 b ON a.col_id= b.col_id) count_of_confirmed_rec, c.col_1 as c_col_1
FROM table_3 c LEFT JOIN table_4 d ON c.col_id = d.col_id 
WHERE d.col_1 = 'value'
) SQ
where c_col_1 = CASE count_of_confirmed_rec WHEN 0 THEN 0 ELSE 1 END