WHERE子句中的列别名

时间:2012-03-12 09:39:35

标签: mysql alias alternate

问题

我在Query中使用备用列名(别名),我可以使用别名“given_name”作为ORDER BY的一部分,但我无法将其用作WHERE子句的一部分。 WHERE“given_name”作为请求的结果传入我的控件之外,我不知道应该在WHERE条件中使用的实际列名。

问题

  1. 在WHERE子句中使用列别名有什么方式/ hack?
  2. 有没有办法从别名中找到列名?
  3. 研究

    经过一些研究后,看起来在WHERE子句之后添加了别名。

    实施例

    SELECT profile.id AS id, given.name AS 'given_name', family.name AS 'family_name'
    FROM green_profile profile 
    LEFT JOIN green_name given ON given.profileid = profile.id AND given.name_typeid = 0 
    LEFT JOIN green_name family ON family.profileid = profile.id AND family.name_typeid = 1 
    WHERE given_name LIKE 'levi%' 
    ORDER BY given_name DESC LIMIT 0 , 25
    

3 个答案:

答案 0 :(得分:4)

未经测试,但这个黑客应该有用......

SELECT * FROM (  
    SELECT profile.id AS id, given.name AS 'given_name', family.name AS 'family_name'
    FROM green_profile profile 
    LEFT JOIN green_name given ON given.profileid = profile.id AND given.name_typeid = 0 
    LEFT JOIN green_name family ON family.profileid = profile.id AND family.name_typeid = 1   
) as temptable
WHERE given_name LIKE 'levi%' 
ORDER BY given_name DESC LIMIT 0 , 25

它只需从原始select语句创建一个临时表(没有where子句和排序),它具有您指定的列名。然后,您可以从中选择所需的列名称。

更好的方法可能是创建一个包含所需列名的视图,然后从视图中选择...

CREATE VIEW newtable AS
SELECT profile.id AS id, given.name AS 'given_name', family.name AS 'family_name'
FROM green_profile profile 
LEFT JOIN green_name given ON given.profileid = profile.id AND given.name_typeid = 0 
LEFT JOIN green_name family ON family.profileid = profile.id AND family.name_typeid = 1;

然后......

SELECT * FROM newtable
WHERE given_name LIKE 'levi%' 
ORDER BY given_name DESC LIMIT 0 , 25

答案 1 :(得分:3)

您只能在GROUP BY,ORDER BY或HAVING子句中使用列别名。

标准SQL不允许您引用WHERE子句中的列别名。强制执行此限制是因为执行WHERE代码时,可能尚未确定列值。

答案 2 :(得分:1)

有疑问,只需按编号参阅列:

...
ORDER BY 2
...