MySQL Query无法找到列

时间:2018-03-04 23:49:08

标签: mysql

我有一个运行正常的查询,当我尝试将另外一列添加到其无法找到列的clouses并给出错误时。

SELECT '1' AS `row_count`, (
    SELECT 
        COUNT(*) 
    FROM 
        `attendances` 
    WHERE `program_sessions`.`id` = `attendances`.`program_session_id` 
    AND `attendances`.`deleted_at` IS NULL
) AS `attendances_count`
FROM
    `program_sessions`
LEFT JOIN `programs` ON `programs`.`id` = `program_sessions`.`program_id`
LEFT JOIN `program_categories` ON `program_categories`.`id` = `programs`.`program_category_id`
LEFT JOIN `service_areas` ON `service_areas`.`id` = `program_categories`.`service_area_id`
LEFT JOIN `locations` ON `locations`.`id` = `programs`.`location_id`
WHERE (
    LOWER(`program_categories`.`name`) LIKE "%3%" OR 
    LOWER(`programs`.`name`) LIKE "%3%" OR 
    LOWER(`locations`.`name`) LIKE "%3%" OR
    (attendances_count = 3) OR 
    LOWER(`service_areas`.`name`) LIKE "%3%"
) 
AND `program_sessions`.`deleted_at` IS NULL

MySQL said: #1054 - Unknown column 'attendances_count' in 'where clause'

查询以某种方式无法到达attendances_count。我做错了什么?

1 个答案:

答案 0 :(得分:1)

在这里发现问题,显然clouse无法看到别名列。我应该使用having代替。

Can you use an alias in the WHERE clause in mysql?