mysql别名的未知列问题

时间:2012-01-27 16:59:56

标签: mysql

当列是创建的别名时,我无法弄清楚为什么我会得到一个未知列。任何帮助都会很棒。

代码:

SELECT DISTINCT 
    c.id, 
    ((SUM(c.width_feet)*12)+(SUM(c.width_inches))) AS width, 
    ((SUM(c.height_feet)*12)+(SUM(c.height_inches))) AS height 
    FROM carpets AS c 
    WHERE c.active = '1' 
    AND (width BETWEEN '0' AND '275') 
    AND (height BETWEEN '0' AND '599') 
    ORDER BY c.item_no 

错误:

  

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

3 个答案:

答案 0 :(得分:11)

您无法直接按名称访问别名。

一种解决方案是使用子查询中的别名包装查询,然后引用外部查询中的别名:

SELECT DISTINCT * 
FROM 
    (
     SELECT c.id, 
          ((SUM(c.width_feet)*12)+(SUM(c.width_inches))) AS width, 
          ((SUM(c.height_feet)*12)+(SUM(c.height_inches))) AS height
     FROM carpets AS c 
     WHERE c.active = '1'
    ) sub
WHERE (sub.width BETWEEN '0' AND '275') 
AND   (sub.height BETWEEN '0' AND '599') 
ORDER BY sub.item_no

答案 1 :(得分:6)

您可以在order by子句中使用别名,但不能在where或group by子句中使用别名。要么重复表达式,要么可以使用子查询。

答案 2 :(得分:0)

我认为你不能在“宽度......和......之间”使用你的“宽度”别名;遗憾的是,你需要重复原始计算。 “身高”相同。因此,以下内容应该有效:

SELECT   DISTINCT c.id, 
         ((SUM(c.width_feet)*12)+(SUM(c.width_inches))) AS width, 
         ((SUM(c.height_feet)*12)+(SUM(c.height_inches))) AS height 
FROM     carpets AS c 
WHERE    c.active = '1' 
AND      (((SUM(c.width_feet)*12)+(SUM(c.width_inches))) BETWEEN '0' AND '275') 
AND      (((SUM(c.height_feet)*12)+(SUM(c.height_inches))) BETWEEN '0' AND '599') 
ORDER BY c.item_no