6

问题

我在查询中使用备用列名(别名),我可以将别名“given_name”用作 ORDER BY 的一部分,但无法将其用作 WHERE 子句的一部分。WHERE "given_name" 是由于我无法控制的请求而传入的,我不知道应该在 WHERE 条件中使用的实际列名。

问题

  1. 有没有办法/hack 在 WHERE 子句中使用列别名?
  2. 有没有办法从别名中找到列名?

研究

经过一些研究,看起来在 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
4

3 回答 3

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

它通过简单地从您的原始选择语句(没有 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
于 2012-03-12T09:44:41.817 回答
3

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

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

于 2012-03-12T09:50:16.570 回答
1

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

...
ORDER BY 2
...
于 2012-03-12T09:41:12.640 回答