2011-03-24 48 views
2

我想得到一個計數,按天分組。下面的SELECT正常工作:爲什麼在MySQL中每個有效的SELECT都不是有效的VIEW?

SELECT COUNT(time_end), 
     time_end 
    FROM main 
GROUP BY DAY(time_end) 

我複製/粘貼到這一點的phpmyadmin的視圖創建的形式,出現此錯誤:

"#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'count(time_end)) AS SELECT count(time_end) , time_end FROM main GROUP BY d' at line 4"

這裏是從的phpmyadmin的形式生成完整的SQL:

CREATE ALGORITHM = UNDEFINED VIEW `count by day` (
    time_end, 
    count(time_end) 
) AS SELECT COUNT(time_end), 
      time_end 
     FROM main 
    GROUP BY DAY(time_end) 

怎麼了?爲什麼有效的SELECT不會自動成爲有效的VIEW創建?謝謝。

回答

4

不知道phpMyAdmin在哪裏獲取該語法。用途:

CREATE VIEW COUNT_BY_DAY AS 
    SELECT COUNT(time_end), 
     time_end 
    FROM main 
GROUP BY DAY(time_end) 

要知道,你是依靠MySQL's hidden column functionality - 在TIME_END值將被適當地(不能上總是返回相同的值,值的數量從增加到選擇依賴)。它也不能移植到大多數數據庫,你必須重新編寫它。

另外,如果你不是按月限制的話,你的計數將會在第28-31天的時間內出現偏差。並非所有月份都有31天。

2

您的查詢唯一錯誤的是您的列名稱沒有反標。

CREATE ALGORITHM = UNDEFINED VIEW count by day (
`count(time_end)` # you needed to put this in backticks
time_end,
) AS SELECT COUNT(time_end),
time_end
FROM main
GROUP BY DAY(time_end)

爲什麼它的價值,你有錯誤的方式列名稱。

您正在使用的語法是查看列名的EXPLICIT NAMING。它允許您爲列指定名稱,否則將從查詢列中導出派生的,例如,

CREATE VIEW X AS 
SELECT time_end, other1 
FROM main 

:: X contains the columns `time_end` and `other1` 

CREATE VIEW X (TheStopTime, DataPoint) AS 
SELECT time_end, other1 
FROM main 

:: X contains the columns `TheStopTime` and `DataPoint` 
相關問題