在别名串联字段中使用 WHERE 会产生 'unknown column' 错误

Using WHERE in aliased concatenated fields gives 'unknown column' error

我有以下查询:

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'

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

您不能在 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

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

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