Mysql选择案例为WHERE

时间:2013-12-28 09:17:15

标签: php mysql

我们不能这样做吗?

SELECT tbl_ads.*, CASE tbl_ads.type
  WHEN 'private'
       THEN (select tbl_privatesellers.privateseller_state from tbl_privatesellers where     tbl_privatesellers.privateseller_id = tbl_ads.privateseller_id  )
  WHEN 'dealer'
       THEN (select tbl_dealer.state from tbl_dealer where tbl_dealer.id = tbl_ads.privateseller_id )
END AS state 
FROM tbl_ads WHERE ad_status = 1 AND state = 'ACT'

作为未知列状态给出错误

2 个答案:

答案 0 :(得分:1)

WHERE子句中没有看到表达式结果,因为在计算行的表达式之前首先检查条件。将其放在HAVING子句中,就像那样

...
HAVING state='ACT'

答案 1 :(得分:0)

在最后,在WHERE子句之前评估SELECT,WHERE子句中的条件不能引用在SELECT中计算的表达式。
将条件从SELECT移动(或复制)到WHERE。

SELECT ..........
FROM tbl_ads 
WHERE ad_status = 1 
  AND  'ACT'  =  
     CASE tbl_ads.type
       WHEN 'private'
       THEN (select tbl_privatesellers.privateseller_state 
             from tbl_privatesellers 
             where     tbl_privatesellers.privateseller_id = tbl_ads.privateseller_id  )
       WHEN 'dealer'
       THEN (select tbl_dealer.state 
             from tbl_dealer 
             where tbl_dealer.id = tbl_ads.privateseller_id )
     END