我有以下查询:
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'
有什么建议吗?请注意,我无法重构查询,因为它是由我正在扩展的类生成的。
答案 0 :(得分:2)
您不能在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
答案 1 :(得分:0)
这与SQL查询的执行顺序有关。
您不能在WHERE子句中放置别名,因为在别名命名之前执行了WHERE子句。 HAVING工作正常,因为在别名命名完成后执行HAVING。