怎么在PostgreSQL中对数组进行遍历(postgresql,数组,遍历,开发技术)

时间:2024-04-29 20:43:53 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

创建一个有数组类型字段的表。

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

怎么在PostgreSQL中对数组进行遍历

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

输出结果:

怎么在PostgreSQL中对数组进行遍历

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:怎么在PostgreSQL中对数组进行遍历的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:php如何实现字符串类型数字转数字类型下一篇:

10 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18