私は通知モーダルと、ユーザーが多くの通知を持ち、通知がユーザー間で送信されるユーザーモーダルを持っています。私は、各ユーザから最新の通知を取得し、それらをタイムスタンプでソートして返す関数が必要です。最新のものとは別のものと順番を選択します
私はBY SELECT ... DISTINCT ORDER使用してみました:、SELECT DISTINCT, ORDER BY expressions must appear in select list
created_at
選択リストに表示されない:このSQLを生成
@notifications = Notification.select("DISTINCT(notifier_id, created_at)").order('created_at DESC')
:SELECT DISTINCT(notifier_id, created_at) FROM "notifications" ORDER BY "notifications"."created_at" DESC, created_at DESC)
を私はエラーを取得だから問題は何ですか?この記事に基づいて
:PG::Error: SELECT DISTINCT, ORDER BY expressions must appear in select list
私はBY ... ORDER BY SELECT ... GROUPを使用してみました:
このSQLを生成@notifications = Notification.select("notifier_id").group("notifier_id").order("MAX(created_at)")
:SELECT "notifications"."notifier_id" FROM "notifications" GROUP BY notifier_id ORDER BY "notifications"."created_at" DESC, MAX(created_at)
が、今、私はこれを取得エラー:column "notifications.created_at" must appear in the GROUP BY clause or be used in an aggregate function
私は集計関数を使用していますので、エラーは何ですか?
UPDATE:
は、このコードを使用する:
@notifications = Notification.select("DISTINCT ON (created_at) created_at, notifier_id").order('created_at DESC')
私はすべてのメッセージのリストを取り戻すのではなく、各送信者からだけで最新の。 documentationから
@messages = Message.select("DISTINCT ON (created_at) created_at, sender_id").order('created_at DESC')
:
エラー出力は基本的に何を修正するかを指示します。あなたはそれをやってみましたか? –
基本的な解決策を説明できますか? – Cbas
2番目の 'GROUP BY'クエリはちょっと面倒です。あなたの希望する結果と一緒にいくつかのサンプルデータを投稿できますか?これはRubyの問題よりもPostgresの問題です。 –