Rails - 为什么SQL返回不正确的结果?

时间:2013-09-19 19:39:34

标签: sql ruby-on-rails ruby activerecord join

我有表格,此表格与 item_views 相关联,此处为结构:

  create_table "item_views", :force => true do |t|
    t.integer  "item_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

当我在数据库上运行此AR查询时:

current_user.items.joins(:item_views).where("item_views.created_at > ? AND item_views.created_at < ?", date_from, date_to+1.day).count
然后在SQL查询后生成

SELECT COUNT(*) FROM "items" INNER JOIN "item_views" ON "item_views"."item_id" = "items"."id" WHERE "items"."user_id" = 1 AND (item_views.created_at > '2013-09-10' AND item_views.created_at < '2013-09-20');

以下是 item_views 表中的数据:

select * from item_views;
1|1|2013-09-10 09:52:11.703811|2013-09-10 09:52:11.703811
2|1|2013-09-13 22:55:56.574696|2013-09-13 22:55:56.574696
3|1|2013-09-15 13:14:19.221074|2013-09-15 13:14:19.221074
4|2|2013-09-16 13:05:39.972383|2013-09-16 13:05:39.972383
5|3|2013-09-16 13:11:25.466117|2013-09-16 13:11:25.466117
6|1|2013-09-16 19:12:44.846686|2013-09-16 19:12:44.846686

(id,item_id,created_at,updated_at)

查询应返回值 3 ,但不是返回 5 - 看起来在查询中忽略条件"items"."user_id" = 1。< / p>

这怎么可能,或者我错过了什么?

由于

1 个答案:

答案 0 :(得分:0)

我无法弄清楚它为什么会返回5. 4看起来是正确答案。

SELECT COUNT(*)
FROM "items" INNER JOIN
     "item_views"
     ON "item_views"."item_id" = "items"."id"
WHERE "items"."user_id" = 1 AND
      (item_views.created_at > '2013-09-10' AND item_views.created_at < '2013-09-20');

数据中的所有6行都符合日期条件。是的,'2013-09-10 09:52:11.703811'大于'2013-09-10'。也许意图是:

WHERE "items"."user_id" = 1 AND
      (date(item_views.created_at) > '2013-09-10' AND
       date(item_views.created_at) < '2013-09-20'
      );

更有效地表达为:

WHERE "items"."user_id" = 1 AND
      (item_views.created_at >= '2013-09-11' AND
       item_views.created_at < '2013-09-20'
      );

您确定没有一行1行吗?在任何情况下,您都应该使用select *而不是select count(*)运行查询,以查看它返回的内容。