DISTINCT ON查询w / ORDER BY列的最大值
我的任务是将一个Rails应用程序从MySQL转换为Postgres asap并遇到一个小问题。
活动记录查询:
current_user.profile_visits.limit(6).order("created_at DESC").where("created_at > ? AND visitor_id ?", 2.months.ago, current_user.id).distinct
生成SQL:
SELECT visitor_id, MAX(created_at) as created_at, distinct on (visitor_id) * FROM "profile_visits" WHERE "profile_visits"."social_user_id" = 21 AND (created_at > '2015-02-01 17:17:01.826897' AND visitor_id 21) ORDER BY created_at DESC, id DESC LIMIT 6
我在使用MySQL时非常自信,但我老实说是Postgres的新手。 我认为这个查询失败的原因有很多。
- 我认为需要先区分。
- 我不知道如何通过max函数的结果来订购
- 我甚至可以使用这样的max函数吗?
此查询的高级目标是返回用户的6个最新配置文件视图。 任何关于如何修复此ActiveRecord查询(或它的结果SQL)的指针将不胜感激。
此查询的高级目标是返回用户的6个最新配置文件视图 。
那很简单。 你不需要max()
和DISTINCT
:
SELECT * FROM profile_visits WHERE social_user_id = 21 AND created_at > (now() - interval '2 months') AND visitor_id <> 21 -- ?? ORDER BY created_at DESC NULLS LAST, id DESC NULLS LAST LIMIT 6;
我怀疑你的问题不完整。 如果你想:
他们最近访问该页面的6位最新访客
那你需要一个子查询。 您无法在一个查询级别中获得此排序顺序,既不能使用DISTINCT ON
,也不能使用窗口函数:
SELECT * FROM ( SELECT DISTINCT ON (visitor_id) * FROM profile_visits WHERE social_user_id = 21 AND created_at > (now() - interval '2 months') AND visitor_id <> 21 -- ?? ORDER BY visitor_id, created_at DESC NULLS LAST, id DESC NULLS LAST ) sub ORDER BY created_at DESC NULLS LAST, id DESC NULLS LAST LIMIT 6;
子查询sub
获取每个用户的最新访问(但不超过两个月而不是某个访问者ORDER BY
必须与DISTINCT ON
具有相同的前导列。
您需要外部查询才能获得最新的6位访问者。
考虑一系列事件:
- 在应用LIMIT之前获得结果计数的最佳方法
为什么NULLS LAST
? 可以肯定的是,您没有提供表定义。
- PostgreSQL按日期时间asc排序,先是null吗?