我的SQL查询:错误:在WHERE子句中使用CASE WHEN时字段列表中的未知列

时间:2014-04-04 04:27:57

标签: mysql

大家好,我是mysql查询的初学者。在mysql中使用此查询时出现一个错误:

SELECT enquiry.business_id ,enquiry_count ,b.`business_name`,c.`id`
FROM `consumer_guide_enquiry_company` enquiry
INNER JOIN `businesses` b ON  `enquiry`.`business_id`=b.`business_id`
INNER JOIN `consumer_guide_company` c ON c.`business_id`=b.`business_id` 
WHERE CASE 
WHEN enquiry.`business_id` 
IN (
SELECT b.business_id 
FROM `businesses` b,`consumer_guide_company` c 
WHERE b.`business_id`=c.`business_id` AND c.`consumer_guide_id`=1) 
THEN enquiry_count=COUNT(enquiry.enquiry_id) 
ELSE enquiry_count=0 
END
GROUP BY enquiry.business_id

显示错误:未知栏' enquiry_count'在'字段列表'

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

你不应该提到名字where is tablename.enquiry_count

以下行中的代码错误:

错误的代码行:1

SELECT enquiry.business_id ,enquiry_count ,b.`business_name`,c.`id`

错误的代码行:2

    THEN enquiry_count=COUNT(enquiry.enquiry_id) 
    ELSE enquiry_count=0 

你应该提到: tablename

   tablename.enquiry_count 

答案 1 :(得分:0)

尝试这样

SELECT enquiry.business_id ,case when enquiry_count is NULL then  0 
else enquiry_count end 'enquiry_count'  ,b.`business_name`,c.`id`
FROM `consumer_guide_enquiry_company` enquiry

INNER JOIN `businesses` b ON  `enquiry`.`business_id`=b.`business_id`
INNER JOIN `consumer_guide_company` c ON c.`business_id`=b.`business_id` 

LEFT JOIN (SELECT b.business_id,count(*) as enquiry_count FROM `businesses`
b,`consumer_guide_company` c WHERE b.`business_id`=c.`business_id` AND  
c.`consumer_guide_id`=1 group by b.business_id) as tt 
ON enquiry.`business_id`=tt.b.business_id
GROUP BY enquiry.business_id