怎么在PostgreSQL中对数组进行遍历
导读:本文共1742字符,通常情况下阅读需要6分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 创建一个有数组类型字段的表。createtabletest_array(idserialprimarykey,str1int[][][]);插入两条测试数据。insertintotest_arrayvalues(1,array[[[1,2],[3,4],[5,6]],[[20,30],[40,50],[70,100]]]);insertintotest_arr... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。创建一个有数组类型字段的表。
createtabletest_array(idserialprimarykey,str1int[][][]);
插入两条测试数据。
insertintotest_arrayvalues(1,array[[[1,2],[3,4],[5,6]],[[20,30],[40,50],[70,100]]]);insertintotest_arrayvalues(2,array[[[100,200],[300,400],[500,600]],[[2000,3000],[4000,5000],[7000,10000]]]);
为了能直观的看到结果集,我们得把数组的值换成普通的类型拿出来, 有以下几种方法。
不带分片的遍历,
createorreplacefunctionsp_array2table_simple(anyarray)returnstable(elementint)as$ytt$declarearray1aliasfor$1;xint;begindroptableifexiststmp_1;createtemporarytabletmp_1(idint);<<label1>>foreachxinarrayarray1loopinsertintotmp_1values(x);endlooplabel1;returnqueryselect*fromtmp_1;end;$ytt$languageplpgsql;t_girl=#selectsp_array2table_simple(str1)asarray_listfromtest_arraywhereid=2;array_list------------1002003004005006002000300040005000700010000(12行记录)时间:7.780ms
带分片的遍历:
createorreplacefunctionsp_array2table(anyarray)returnstable(elementint)as$ytt$declarearray1aliasfor$1;xint[];nlenint:=0;iint:=1;begindroptableifexiststmp_1;createtemporarytabletmp_1(idint);<<label1>>foreachxslice1inarrayarray1loopnlen:=array_length(x,1);i:=1;<<label2>>whilei<=nlenloopinsertintotmp_1values(x[i]);i:=i+1;endlooplabel2;endlooplabel1;returnqueryselect*fromtmp_1;end;$ytt$languageplpgsql;t_girl=#selectsp_array2table(str1)asarray_listfromtest_arraywhereid=2;array_list------------1002003004005006002000300040005000700010000(12行记录)时间:20.139ms
还有就是系统系统了几个函数,直接进行遍历,
比如unnest
t_girl=#selectunnest(str1)asarray_listfromtest_arraywhereid=2;array_list------------1002003004005006002000300040005000700010000(12行记录)时间:1.002ms
比如array_to_string 等。
t_girl=#selectregexp_split_to_table(array_to_string(str1,','),',+')asarray_listfromtest_arraywhereid=2;array_list------------1002003004005006002000300040005000700010000(12行记录)时间:0.850ms
补充:PostgreSQL遍历Json
SQL:
SELECTorderno,fromno,fromamount,fromlotno->>'index'fromlotno,othercondition->>'supplicode'supplicode,othercondition->>'downcode'downcode,othercondition->>'spec'spec,othercondition->>'carport'carportFROM(SELECTorderno,fromno,fromamount,json_array_elements(fromlotno)fromlotno,json_array_elements(othercondition)otherconditionFROMt_feather_source)A
输出结果:
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:
怎么在PostgreSQL中对数组进行遍历的详细内容,希望对您有所帮助,信息来源于网络。