如何在SQL中使用空虚拟列过滤查询?

时间:2018-04-13 11:49:13

标签: mysql sql

我的情况是必须比较中的空虚字段

SELECT id, name, contact, landline, '' fax
FROM table1 
WHERE contact LIKE '%123%'
   OR landline LIKE '%123%'
   OR fax LIKE '%123%'

执行后会出现如下错误:

  

'where子句'中的未知列'fax'

有可能吗?

2 个答案:

答案 0 :(得分:3)

这是不可能的;您不能使用SELECT中相同WHERE中定义的别名。

MySQL扩展了HAVING子句的使用范围,因此您可以将条件移至HAVING

SELECT id, name, contact, landline, '' as fax
FROM table1
HAVING contact LIKE '%123%' OR landline LIKE '%123%' OR fax LIKE '%123%'

答案 1 :(得分:2)

将原始查询包装在派生表(子查询)中。在结果上应用条件:

select id, name, contact, landline, fax
from
(
    SELECT id, name, contact, landline, '' fax
    FROM table1 
) dt
WHERE contact LIKE '%123%'
   OR landline LIKE '%123%'
   OR fax LIKE '%123%'

ANSI SQL兼容解决方案,适用于大多数dbms产品。