我有两个ActiveRecord查询。一个返回4,这是正确的数字,另一个返回11,这是错误的计数。我希望两个查询都返回4.即使在Rails控制台中呈现的SQL对于两个AR查询都是相同的。
首先查询:
campaign.daily_statistics.select('COUNT(DISTINCT user_id) AS count').where(metric: metric).where("properties -> '#{column}' = '#{value}'")[0]['count']
DailyStatistic Load (0.7ms) SELECT COUNT(DISTINCT user_id) AS count FROM "daily_statistics" WHERE "daily_statistics"."campaign_id" = $1 AND "daily_statistics"."metric" = 'participation' AND (properties -> 'assumed_gender' = 'female') [["campaign_id", 2]]
=> 4
第二次查询:
sql = campaign.daily_statistics.select('COUNT(DISTINCT user_id) AS count')
sql.where(metric: metric).where("properties -> '#{column}' = '#{value}'")
sql[0]['count']
DailyStatistic Load (0.9ms) SELECT COUNT(DISTINCT user_id) AS count FROM "daily_statistics" WHERE "daily_statistics"."campaign_id" = $1 AND "daily_statistics"."metric" = 'participation' AND (properties -> 'assumed_gender' = 'female') [["campaign_id", 2]]
=> 11
有人能解释一下这里发生了什么吗?
答案 0 :(得分:1)
在您的第二个查询中,您未分配
sql.where(metric: metric).where("properties -> '#{column}' = '#{value}'")
任何事情。所以当你运行时
sql[0]['count']
您只执行分配给sql变量的查询的第一部分。
我不确定为什么SQL日志记录输出会像它一样出现。据猜测,由于rails控制台的某些特性以及提供输出/内联日志记录的原因。
答案 1 :(得分:0)
您应该在rails控制台中看到的内容如下:
sql = campaign.daily_statistics.select('COUNT(DISTINCT user_id) AS count')
DailyStatistic Load (0.9ms) SELECT COUNT(DISTINCT user_id) AS count FROM "daily_statistics" WHERE "daily_statistics"."campaign_id" = $1) [["campaign_id", 2]]
sql.where(metric: metric).where("properties -> '#{column}' = '#{value}'")
DailyStatistic Load (0.9ms) SELECT COUNT(DISTINCT user_id) AS count FROM "daily_statistics" WHERE "daily_statistics"."campaign_id" = $1 AND "daily_statistics"."metric" = 'participation' AND (properties -> 'assumed_gender' = 'female') [["campaign_id", 2]]
sql[0]['count']
#=> 11
第二个查询的修复应该是:
sql = campaign.daily_statistics.select('COUNT(DISTINCT user_id) AS count')
DailyStatistic Load (0.9ms) SELECT COUNT(DISTINCT user_id) AS count FROM "daily_statistics" WHERE "daily_statistics"."campaign_id" = $1) [["campaign_id", 2]]
sql2 = sql.where(metric: metric).where("properties -> '#{column}' = '#{value}'")
DailyStatistic Load (0.9ms) SELECT COUNT(DISTINCT user_id) AS count FROM "daily_statistics" WHERE "daily_statistics"."campaign_id" = $1 AND "daily_statistics"."metric" = 'participation' AND (properties -> 'assumed_gender' = 'female') [["campaign_id", 2]]
sql2[0]['count']
#=> 4