以下は私の質問です:
SELECT *
FROM (
SELECT f.max, f.min, p.user_id, p.id, p.title, p.rating,
RANK() OVER (
PARTITION BY p.user_id
ORDER BY p.rating DESC, p.id DESC
) AS rnk
FROM posts AS p
INNER JOIN friends AS f ON (p.user_id = f.friend_id)
WHERE f.user_id=1
) AS subq
WHERE (subq.rnk <= subq.max)
LIMIT 10
友達の投稿を検索し、評価と日付で並べ替えます。このクエリに実装されたウィンドウ関数により、テーブルのMAX
フィールドに従って、各フレンドに対して返される行数を制限できFriends
ます。
ただし、フィールドもありますMIN
。これは、特定の友人のクエリから必要な投稿の最小数を指定するために使用されます。そんなことがあるものか?
また、これらのタイプのクエリには SQL が最適なオプションなのだろうか? 私はすでに Neo4j Graph データベースを試しました。これは良い解決策のように思えましたが、2 つの別々のデータベースを使用することは避けたいと思います。
スキーマ:
CREATE TABLE friends(
user_id int,
friend_id int,
min int,
max int
);
CREATE TABLE posts(
id int,
title varchar(255),
rating int,
date date,
user_id int
);
次のデータがあるとします。
INSERT INTO friends VALUES
(1,2,1,3)
, (1,3,0,5)
, (1,4,2,10);
INSERT INTO posts VALUES
(1, 'posts1', 2, now(), 2)
, (2, 'posts2', 1, now(), 2)
, (3, 'posts3', 5, now(), 2)
, (4, 'posts4', 2, now(), 2)
, (5, 'posts5', 11, now(), 2)
, (6, 'posts6', 7, now(), 2)
, (7, 'posts7', 3, now(), 2)
, (8, 'posts8', 4, now(), 3)
, (9, 'posts9', 1, now(), 3)
, (10, 'posts10', 0, now(), 3)
, (11, 'posts11', 7, now(), 3)
, (12, 'posts12', 3, now(), 3)
, (13, 'posts13', 2, now(), 3)
, (14, 'posts14', 4, now(), 4)
, (15, 'posts15', 9, now(), 4)
, (16, 'posts16', 0, now(), 4)
, (17, 'posts17', 3, now(), 4)
, (18, 'posts18', 2, now(), 4)
, (19, 'posts19', 1, now(), 4)
, (20, 'posts20', 2, now(), 4);
(post_id, title, rating, date, friend_id)
したがって、可能であれば、次の条件との組み合わせを確認したいと考えています。
id
=2の友人からの 1 ~ 3 件の投稿id
=3の友達からの 0 ~ 5 件の投稿id
=4の友人からの 2 ~ 10 件の投稿
基本的に、私の友人がfriend_id=2
1 つ以上の記事を投稿している場合、少なくとも 2 つの記事が必要です。彼が 3 つ以上の記事を投稿した場合、私は 3 つを超えないようにします。