次のようなテーブルがあります。
create table images (
image_id serial primary key,
user_id int references users(user_id),
date_created timestamp with time zone
);
次に、画像が持つことができるタグのタグ テーブルがあります。
create table images_tags (
images_tag_id serial primary key,
image_id int references images(image_id),
tag_id int references tags(tag_id)
);
必要な結果を得るために、次のようなクエリを実行します。
select image_id,user_id,tag_id from images left join images_tags using(image_id)
where (?=-1 or user_id=?)
and (?=-1 or tag_id in (?, ?, ?, ?)) --have up to 4 tag_ids to search for
order by date_created desc limit 100;
image_id
問題は、出力が次のようになるため、一意の の数に基づいて制限したいことです。
{"images":[
{"image_id":1, "tag_ids":[1, 2, 3]},
....
]}
SQL はそれぞれとコンボtag_id
に対して行を返しますが、s を出力用の配列にグループ化する方法に注意してください。tag_id
image_id
だから、私が言うときlimit 100
、私はそれを100のユニークな に適用したいimage_id
.