【问题标题】:Using WHERE in aliased concatenated fields gives 'unknown column' error在别名连接字段中使用 WHERE 会产生“未知列”错误
【发布时间】:2015-12-18 09:17:11
【问题描述】:

我有以下疑问:

SELECT a.*, CONCAT_WS(' ', `c`.`firstname`, `c`.`lastname`) AS `customer_fullname`
FROM `tickets` a        
LEFT JOIN `customers` `c` ON (`a`.`id_customer` = `c`.`id_customer`)
WHERE a.`id_raffle` = 1  AND `customer_fullname` LIKE '%John%'
ORDER BY a.`id_ticket` ASC LIMIT 0,50

我得到了错误:

Unknown column 'customer_fullname' in 'where clause'

有什么建议吗?请注意,我无法重构查询,因为它是由我正在扩展的类生成的。

【问题讨论】:

    标签: mysql sql select where alias


    【解决方案1】:

    您不能在 WHERE 子句中使用列别名。

    试试这个:

    SELECT a.*, CONCAT_WS(' ', `c`.`firstname`, `c`.`lastname`) AS `customer_fullname`
    FROM `tickets` a        
    LEFT JOIN `customers` `c` ON (`a`.`id_customer` = `c`.`id_customer`)
    WHERE a.`id_raffle` = 1  AND CONCAT_WS(' ', `c`.`firstname`, `c`.`lastname`)  LIKE '%John%'
    ORDER BY a.`id_ticket` ASC 
    LIMIT 0,50
    

    或

    SELECT a.*, CONCAT_WS(' ', `c`.`firstname`, `c`.`lastname`) AS `customer_fullname`
    FROM `tickets` a        
    LEFT JOIN `customers` `c` ON (`a`.`id_customer` = `c`.`id_customer`)
    WHERE a.`id_raffle` = 1  AND (`c`.`firstname` LIKE '%John%' OR `c`.`lastname` LIKE '%John%') 
    ORDER BY a.`id_ticket` ASC 
    LIMIT 0,50
    

    【讨论】:

    • 正如我所说,我无法重构查询。所以别名是进入 WHERE 的内容。幸运的是,经过更多的挖掘,我发现我可以使用 HAVING,它似乎可以使用别名。谢谢你的回答。
    • @Marc 我们不能将别名放在 where 子句中。你必须将 concat 函数放在 where 子句中或 pur OR 运算符放在 where 子句中
    【解决方案2】:

    这与 SQL 查询的执行顺序有关。

    您不能将别名放在 WHERE 子句中,因为 WHERE 子句在别名命名之前执行。 HAVING 工作正常,因为 HAVING 是在别名命名完成后执行的。

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 2017-05-31
      • 2020-10-03
      • 1970-01-01
      • 2016-02-29
      • 2015-08-27
      • 2023-03-15
      相关资源
      最近更新 更多