[pgsql-jp: 34579] Re: 自分のテーブルのローを削除したい。

ISHIDA Akio iakio @ mono-space.net
2004年 12月 28日 (火) 18:54:49 JST


こんにちは。石田@苫小牧市です。

渡辺 伸雄 wrote:
> テーブルXにmemberIDとAssignTimeがあるとします。
> 
> X
> memberID AssignTime
> 1 2004/12/28 17:00:00
> 1 2004/12/28 18:00:00
> 2 2004/12/28 17:50:00
> 
> この中で最初のローだけを削除したいのです。
> 
> deleteした結果は
> X
> memberID AssignTime
> 1 2004/12/28 18:00:00
> 2 2004/12/28 17:50:00
> としたいのです。
> 
> で、思いついたSQLが次のSQLなのですが、
> 何か反則気味な感じがします。
> 
> delete from X
> where not oid in (select x2.oid from
> (select max(AssignTime) as ma,memberid from x)x1
> join
> x x2
> on x1.memberid=x2.memberid and x1.ma=x2.assigntime);
> 
> oidを使うのは良くない気がしますし、
> カーソルなどを使うのでしょうか?
> もっと、さっぱりした方法を知りたいのですが。
> よろしくお願いします。

oidのかわりに、(memberid, assigntime)を使います。

delete from x
  where not (memberid, assigntime) in
           (select x2.memberid, x2.assigntime
              from (select max(assigntime) as ma, memberid
                      from x
                     group by memberid) x1
                   join x x2
                   on (x1.memberid = x2.memberid
                  and x1.ma = x2.assigntime))

重複した値があった場合の挙動は違いますが、これでもいけます。

delete from x
  where not (memberid, assigntime) in
           (select x2.memberid, x2.assigntime
              from x x2
             where x.memberid = x2.memberid
             order by x2.assigntime
             limit 1)

-- 
ISHIDA Akio <iakio @ mono-space.net / ishida @ cycleof5th.com>



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