超長sql文の使い方のまとめ


以前はsql文を書くのに効率を考えなかったが、今はこの考えを変えなければならない.
 
データベースの記録は何百万ものデータですね.
select c.name ,a.   2008 12 31 ,b.   2009 3 31  from city_code  c left join 
 (select g.cityid as cid, count(g.cityid)    2008 12 31  from group_info g where
 g.typeid=5
 and g.regtime<=to_date('20081231','yyyymmdd')
 group by g.cityid)
 a 
on a.cid=c.nid
left join 
 (select g.cityid as cid, count(g.cityid)    2009 3 31  from group_info g where
 g.typeid=5
 and g.regtime<=to_date('20090331','yyyymmdd')
 group by g.cityid)
 b 
on b.cid=c.nid

 
注意aの前はas、bの前も使えません.
別名はあまり長くも引用符を打つことはできません.
group_infoテーブルのデータ量は大きく、city_codeは和コードテーブルなので、基準テーブルとして選択します.
to_dateメソッドはdateタイプを返します.結果は次のとおりです.
	  	9658	10445
	  	1051	2310
	  	688	732
	  	1733	1749
	  	2651	4145
	  	1136	1500
	  	2120	2121
	  	2112	2511	
                  		2184
	  	719	719
	  	1010	1088
	  	752	988
	  	729	729
	  	1533	1566

 
 
更新:
 
 
update card_info ci
     set ci.status     = 3,
         ci.statusdate = (select distinct act_date
                            from tempc_active_card ai
                           where ai.cardno = ci.cardno)
   where ci.status = 0
     and ci.cardno in (select cardno from tempc_active_card);
     

 
この中の更新はとても面白いです.statusdateの値は、従来は定数を与えていましたが、ここでは定数を与えています.
条件を満たす値はcardnoが唯一なので、返される値はまだ1つです.実質は変わらない.