How to refer 'decider' in the where clause from the following mysql query?

陌路散爱 提交于 2019-12-11 10:58:58

问题


How to refer 'decider' in the where clause from the following mysql query?

SELECT *, 
       CASE
         WHEN (cond1) THEN 1
         WHEN (cond2) THEN 2
       END as decider
  FROM t1,
       t2 
 WHERE cond12
   AND decider <> NULL

I tried it, and I got a 1054: Unknown column in where clause error.


回答1:


Use:

SELECT *, 
       CASE
         WHEN (cond1) THEN 1
         WHEN (cond2) THEN 2
         ELSE NULL
       END as decider
  FROM t1,
       t2 
 WHERE cond12
HAVING decider IS NOT NULL
  1. The earliest MySQL allows you to use column aliases is the GROUP BY clause
  2. You need to use IS NULL or IS NOT NULL (where appropriate) because NULL is not a value -- it's a placeholder for the lack of any value, which requires special handling in SQL


来源:https://stackoverflow.com/questions/6209383/how-to-refer-decider-in-the-where-clause-from-the-following-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!