2011-08-31 124 views
0

因此,這裏的整個事情:SQL LIMIT語法錯誤

SELECT * FROM sometable LIMIT 5*DATEDIFF(NOW(), '2011-08-30'), 5 

錯誤:

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 '*DATEDIFF(NOW(), '2011-08-30'), 5' at line 1

的問題顯然是LIMIT顯然並未接受任何東西,但整數。它也不會接受1+1(1+1)。有沒有辦法解決它?

只是所以你不必去試試,5*DATEDIFF(NOW(), '2011-08-30')工作得很好。

我試圖修復this答案..

+1

[這個問題](http://stackoverflow.com/questions/5872667/how-to-make-limit-offset-dynamic-using-only-mysql)可能會幫助你,如果你想要在SQL中完成它,但是AFAIK,你不能在MySQL的LIMIT子句中進行計算。 –

+0

看起來真的沒有辦法繞過它,但還有其他的事情可以做。例如,運行單獨的查詢來選擇datediff,將其作爲變量保存在您使用的任何編程語言中,並將其插入到上面的查詢中。無論是那個,或者你可以通過其他方式先計算datediff(例如使用php日期函數) –

+0

甚至不能使用服務器端的var,所以'select @lim:= datediff(...);選擇.... limit @ lim,1'也會失敗。 –

回答

2

NO,不是純的MySQL可行
(但是,通過存儲過程是可能的,用戶定義的函數)

的情況下,可以通過PHP調用輕鬆替換

$offset = 5* 
     date_diff(new DateTime('now'), new DateTime('2011-08-31'))->format('%a'); 
$sql = "SELECT * FROM sometable LIMIT {$offset},5"; 
+0

格式必須是%d,而不是%a –

1

限制必須是整數或局部變量。從MySQL docs

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions:

  • Within prepared statements, LIMIT parameters can be specified using ? placeholder markers.

  • Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables as of MySQL 5.5.6.

+0

我試圖找到這個,但是我找不到它。謝謝 –