开发者

Rails console query returns different results compared to pure sql query

开发者 https://www.devze.com 2023-02-23 04:26 出处:网络
So in my Rails console I have an active record query that generates an SQL. I look in my logs/development and I can see the SQL that is being generated.

So in my Rails console I have an active record query that generates an SQL. I look in my logs/development and I can see the SQL that is being generated.

For some reason I'm not getting the expected results when I run the active record query. I looked into my logs and copied/pasted the sql into the console that is connected to my database and then suddenly that returns the correct results. Any ideas why this is happening? I'm using PostgreSQL.

I'm trying to find stores that were opened in the past 5 hours.

EDIT subtracting 10 hours makes this query work....

ActiveRecord call (within is from geokit gem):

Store.within(10, :origin =>[30.267153000000000, -97.743060799999970]).where("date > current_timestamp - interval '5 hours'")

SQL generated:

SELECT "store".*, 
 (ACOS(least(1,COS(0.5282614750548792)*COS(-1.705938231937002)*COS(RADIANS(store.lat))*COS(RADIANS(store.lng))+
 COS(0.5282614750548792)*SIN(-1.705938231937002)*COS(RADIANS(store.lat))*SIN(RADIANS(store.lng))+
 SIN(0.5282614750548792)*SIN(RADIANS(store.lat))))*3963.19)
 AS distance FROM "store" WHERE ((store.lat>30.122583147146404 AND store.lat<30.41172285285359 AND store开发者_高级运维.lng>-97.91044799232348 AND store.lng<-97.57567360767642)) AND ((
 (ACOS(least(1,COS(0.5282614750548792)*COS(-1.705938231937002)*COS(RADIANS(store.lat))*COS(RADIANS(store.lng))+
 COS(0.5282614750548792)*SIN(-1.705938231937002)*COS(RADIANS(store.lat))*SIN(RADIANS(store.lng))+
 SIN(0.5282614750548792)*SIN(RADIANS(store.lat))))*3963.19)
 <= 10)) AND (date > current_timestamp - interval '5 hours')


. . . .where("date > current_timestamp - interval '5 hours'")

Standard SQL syntax for this WHERE clause should be

WHERE "date" > current_timestamp - interval '5' hour

In standard SQL, date is a reserved word; reserved words used as column names need to be in double quotes. Note that the number is within single quotes, and that the keywords interval and hour aren't quoted. Support for standard SQL varies wildly, especially in your neighborhood. (Quoting of reserved words and date arithmetic.)

So . . . check the docs for your target platform to make sure you're quoting (or not quoting) these two things correctly.

I'm having a hard time convincing myself that this could the the cause of your problem, though.

0

精彩评论

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

关注公众号