【问题标题】:MySQL Query cannot find column [duplicate]MySQL Query 找不到列 [重复]
【发布时间】:2018-03-04 23:49:08
【问题描述】:

我有一个运行良好的查询,当我尝试向 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。我到底做错了什么?

【问题讨论】:

  • 来自SELECT 子句中相关子查询的计数是否有意义?您正在计算超过五个连接表。
  • @TimBiegeleisen 是的,必须如此。不过它们是简单的表格。
  • 我将探索以下内容以了解它是否适​​用于您的查询:搜索WITH 语句 - stackoverflow.com/questions/3241352/…dev.mysql.com/doc/refman/8.0/en/with.html 。但这不是下面提到的简单解决方案(也许这里的优化在于您只是在过滤出勤人数 = 3 的地方)。但是WITH 值得研究学习,看看它是否能解决您的问题,但同样不要将其用作首选,因为似乎提到了一个更简单的解决方案

标签: mysql


【解决方案1】:

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

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

【讨论】:

  • 是的,这会起作用(仅在 MySQL 上),但我认为我们可以重写您的查询以避免使用 HAVING
  • 我很想看看你会怎么写。
  • @Strawberry 我相信您可以节省我的时间并告诉我正确的解决方案。
  • 你们这些人推动随机开发人员强迫自己有什么问题?如果我有时间和知识,我会问这个问题吗?我妈妈也可以告诉我......“我相信你会从自己解决这个问题中获得更大的好处”
  • 您当然可以将查询重写为与attendances 表的连接。但我需要查看更多数据。您当前的子查询对我来说看起来很奇怪。
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 2019-06-23
  • 2019-03-13
  • 2017-05-22
相关资源
最近更新 更多