在mysql中通过重命名列进行过滤

时间:2011-08-22 16:30:56

标签: mysql

我有以下查询:

SELECT 
IFNULL(CHAR_LENGTH(fiedl1), 0) +
IFNULL(CHAR_LENGTH(fiedl2), 0) +
IFNULL(CHAR_LENGTH(fiedl3), 0) +
IFNULL(CHAR_LENGTH(fiedl4), 0) +
IFNULL(CHAR_LENGTH(fiedl5), 0) +
IFNULL(CHAR_LENGTH(fiedl6), 0) AS L
FROM mytable;

我只想要L小于100的记录。如果我使用WHERE子句,那么我得到“错误代码:1054。'where子句'中的未知列'L'”

2 个答案:

答案 0 :(得分:3)

使用HAVING子句:

SELECT 
IFNULL(CHAR_LENGTH(fiedl1), 0) +
IFNULL(CHAR_LENGTH(fiedl2), 0) +
IFNULL(CHAR_LENGTH(fiedl3), 0) +
IFNULL(CHAR_LENGTH(fiedl4), 0) +
IFNULL(CHAR_LENGTH(fiedl5), 0) +
IFNULL(CHAR_LENGTH(fiedl6), 0) AS L
FROM mytable
WHERE field1 = "yes"
HAVING L < 100;

答案 1 :(得分:2)

尝试使用派生表:

SELECT L FROM 
(
    SELECT  
    IFNULL(CHAR_LENGTH(fiedl1), 0) + 
    IFNULL(CHAR_LENGTH(fiedl2), 0) + 
    IFNULL(CHAR_LENGTH(fiedl3), 0) + 
    IFNULL(CHAR_LENGTH(fiedl4), 0) + 
    IFNULL(CHAR_LENGTH(fiedl5), 0) + 
    IFNULL(CHAR_LENGTH(fiedl6), 0) AS L 
    FROM mytable
)  AS R
WHERE L < 100;