2017-03-06 96 views
1

這樣的簡單查詢。它爲什麼是語法錯誤?

MyModel.where('student_id = :id AND from <= :date AND to >= :date', {:id => student.id, :date => day.to_s(:db)}) 

返回一個例外

=> ActiveRecord::JDBCError: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'from <= '2017-02-28 00:00:00.000' AND to >= '2017-02-28 00:00:00.000')' 

而且我不知道爲什麼。

+3

'FROM'是MySQL的一個保留關鍵字 – Raptor

+0

@Raptor拍攝。這就是我想到的。但我的桌子上有一個來自'from'的字段。那我該怎麼辦? – Viktor

+0

簡單:重命名它。避免在列名稱中使用保留字以及表名。 – Raptor

回答

4

從是保留字,當你有一個列名,你應該使用backtics from(更好,如果你不使用基於保留字列名)

MyModel.where('student_id = :id 
        AND `from` <= :date 
        AND `to` >= :date', {:id => student.id, :date => day.to_s(:db)}) 
+1

由於*相同的*問題在這裏(SO)解決了數百次,所以我沒有看到給出這個問題的答案。像你這樣的用戶(有經驗的人+你已經註冊了MySQL徽章)應該把這些問題作爲重複來解決。 –