[pgsql-jp: 35279] Re: 1件ずつ×4+ランダム2件 のような柔軟な取得方法について

水野 圭 kiyoshi_mizuno @ mail.toyota.co.jp
2005年 4月 18日 (月) 16:23:33 JST


水野です。

> このようなテーブルから「大阪の取扱商品で最新(Idが最大)のものを1件、東京で
> 最新のものを1件、名古屋で最新のものを1件、福岡で最新のものを1件、残りの商
> 品からランダムに2件を取得(取得順もこの通り)」して計6個の商品をリストアッ
> プしたいのですが、これを実現するために以下のようなSQLを使用しました。

「SQL一発」でなくてもよければ、

select id into id1 from Table where shop = '大阪' order by id desc limit 1
select id into id2 from Table where shop = '東京' order by id desc limit 1
select id into id3 from Table where shop = '名古屋' order by id desc limit 1
select id into id4 from Table where shop = '福岡' order by id desc limit 1
の後に
select * from Table where  order by where ( id <>id1 and ... and id <> id4 )
  order by random() limit 2
として上の4件と重複していない2件をselectする、という方法などはどうでしょうか。
書ける人ならこれを1つのSQLでうまく書けると思うのですが、私には書けない
(今はちょっと書き方を調べる時間もないので。)




pgsql-jp メーリングリストの案内