尝试执行此查询:
获得模型user
,profile
,integrations
Profile
有一个meta_data
列,它是hstore并且有一个键twitter_followers
这是我当前的查询,我想订购:
current_user.profiles.where(found: true).select("DISTINCT ON(profiles.id) profiles.id, *, integration_profiles.data as integration_profiles_data, integrations.provider as integration_providers, profiles.*").includes(:integrations).page(params[:page]).per_page(50)
理想情况下:
current_user.profiles.where(found: true).select("DISTINCT ON(profiles.id) profiles.id, *, integration_profiles.data as integration_profiles_data, integrations.provider as integration_providers, profiles.*").includes(:integrations).reorder("CAST(meta_data -> '#{params[:sort_by]}' AS INT) DESC NULLS LAST").page(params[:page]).per_page(50)
但是得到这个错误:
PG::InvalidColumnReference: ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
我试过了:
current_user.profiles.where(found: true).select("DISTINCT ON(profiles.id) profiles.id, *, integration_profiles.data as integration_profiles_data, integrations.provider as integration_providers, profiles.*").includes(:integrations).reorder("profiles.id, CAST(meta_data -> '#{params[:sort_by]}' AS INT) DESC NULLS LAST").page(params[:page]).per_page(50)
.to_sql
=> "SELECT DISTINCT ON(profiles.id) profiles.id, *, integration_profiles.data as integration_profiles_data, integrations.provider as integration_providers, profiles.* FROM \"profiles\" INNER JOIN \"integration_profiles\" ON \"profiles\".\"id\" = \"integration_profiles\".\"profile_id\" INNER JOIN \"integrations\" ON \"integration_profiles\".\"integration_id\" = \"integrations\".\"id\" WHERE \"integrations\".\"user_id\" = $1 AND \"profiles\".\"found\" = 't' ORDER BY profiles.id, CAST(meta_data -> 'twitter_followers' AS INT) DESC NULLS LAST"
没有骰子。它删除了错误,但没有以任何形式订购!