【问题标题】:MYSQL: Doing a where on a own defined parameter in SELECTMYSQL:在 SELECT 中对自己定义的参数执行 where
【发布时间】:2014-05-12 19:11:09
【问题描述】:

当我使用 AS 定义执行 SELECT 语句并且我想对其进行过滤时,它会给出以下错误:#1054 - 'where 子句'中的未知列 'TimeInSeconds'

代码:

Select Id, time/10000000 as TimeInSeconds FROM Results WHERE
TimeInSeconds > 5 AND
TimeInSeconds < 36000

我了解 TimeInSeconds 不是原始表的一部分的错误,但有没有办法使用这些定义的列?

【问题讨论】:

  • 您可以使用WHERE time/10000000... 或将其放在子查询中...

标签: mysql sql select parameter-passing where


【解决方案1】:

也可以使用HAVING子句过滤掉自定义别名的结果

Select Id, `time`/10000000 as TimeInSeconds 
FROM Results 
HAVING TimeInSeconds > 5 AND TimeInSeconds < 36000

或使用WHERE 子句重复表达式

Select Id, `time`/10000000 as TimeInSeconds 
FROM Results 
WHERE (`time`/10000000) > 5 AND (`time`/10000000) < 36000

【讨论】:

    【解决方案2】:

    一种选择是将结果放入subquery

    Select Id, timeinseconds
    From (Select Id, time/10000000 as TimeInSeconds FROM Results) t
    Where TimeInSeconds > 5 AND TimeInSeconds < 36000
    

    【讨论】:

      【解决方案3】:

      最有效的方法是:

      select id, time/10000000 TimeInSeconds
      from results
      where time > 5 * 10000000
      and time < 36000 * 10000000
      

      原因是您的字段直接与值进行比较。子查询方法在过滤结果之前选择整个 darn 表。对 where 子句中的字段进行数学运算(例如使用公式)往往很慢。

      如果相关字段被编入索引,这一点就更重要了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-21
        • 1970-01-01
        • 2020-05-19
        • 2021-02-06
        • 1970-01-01
        • 2022-07-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多