开发者

Rails/Rails3 SQL query, "LIKE" doesn't work with datetimes properly?

Are rails SQL queries actually compatible with datetimes?

For example, if I do:

User.where("email LIKE ?", "%.com%")

I would expect to (and do) get back a list of all users with a ".com" email address.

However, if I do:

User.where("created_at LIKE ?","%2011%")

I get back nothing, even though I can see that there are users created this year. In point of fact, sometimes i get gibberish back (for example, I might get stuff (with seem开发者_如何学JAVAingly nothing in common) back for %20%, but nothing back for %30% even though I know there are dates with a 30 in them), which makes me think the "LIKE" is applying to something I don't see/care about (maybe some sort of ID?)

Are LIKES for string only? Is there some way I can do something similar for date times, in rails (I'm sure there's some way to do it in mysql, but can rails also handle it?)

Specifically, I want to use this in a scope, similar to:

 scope :by_date, lambda {|date| where("created_at LIKE ?",date)}


dt = Date.new(2011,1,1)
User.where(['created_at >= ? AND created_at < ?',dt,dt+1.year])

produces

SELECT "users".* FROM "users" WHERE (created_at >= '2011-01-01' AND created_at < '2012-01-01')

Which is a better way to handle datetimes IMHO


IIRC, datetime values are stored as integers. LIKE operator works on strings.

You can try using CONVERT() or CAST() or even CONCAT().

Something like:

 CONVERT(created_at, VARCHAR(20))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜