如何在WHERE子句中使用别名列日?

时间:2018-02-04 08:37:26

标签: mysql sql

我对此查询有疑问:

  SELECT DAYOFYEAR(t.ts_start) AS 'day', YEAR(t.ts_start) AS year, t.o AS value FROM Cryptoforecast_ETH_BTC_1h AS t 

当我运行它时会显示结果。现在我想过滤一天添加WHERE语句,如此

SELECT DAYOFYEAR(t.ts_start) AS 'day', YEAR(t.ts_start) AS year, t.o AS value FROM Cryptoforecast_ETH_BTC_1h AS t WHERE 'day'=157

但它没有结果和警告:

Truncated incorrect DOUBLE value: 'day'

有什么问题?

2 个答案:

答案 0 :(得分:1)

您无法在WHERE子句中使用别名列。因此,您实际上并不是将列与字符串值进行比较而是使用int。

WHERE 'day'=157

而你可以使用

WHERE DAYOFYEAR(t.ts_start) = 157

旁注:您不需要为列别名使用单引号。

答案 1 :(得分:1)

只需在DAYOFYEAR子句中重复调用WHERE

SELECT
    DAYOFYEAR(t.ts_start) AS day,
    YEAR(t.ts_start) AS year,
    o AS value
FROM Cryptoforecast_ETH_BTC_1h
WHERE DAYOFYEAR(t.ts_start) = 157;

或者,如果您想使用day别名,可以使用重载的HAVING子句来执行此操作:

SELECT
    DAYOFYEAR(t.ts_start) AS day,
    YEAR(t.ts_start) AS year,
    o AS value
FROM Cryptoforecast_ETH_BTC_1h
HAVING day = 157;