2013-01-21 65 views
0

我在SQL的查詢導致2列它們是座標:PostgreSQL的陣列轉

{LAT1,LAT2,lat3}和{lon1,lon2,lon3}

在這樣一種方式,元件在相同的位置將引用相同的對象(再次在另一列中稱爲數組)。

的這看起來是這樣的:

 
objects   latitudes  longitudes 
---------------------------------------------- 
{1,2,3}  | {lat1,lat2,lat3} | {lon1,lon2,lon3} 

我想要做的就是有經/緯夫婦,因爲這:

 
objects   coords 
---------------------------------------------- 
{1,2,3}  | {{lat1,lon1},{lat2,lon2},{lat3,lon3}} 

,甚至是這樣的:

 
objects   coords 
---------------------------------------------- 
{1,2,3}  | {{1,lat1,lon1},{2,lat2,lon2},{3,lat3,lon3}} 

如何在postgresql中完成此操作?

回答

0

我認爲最簡單的方法是閱讀它們,做一個爆炸,然後再放回一個新的數組中。

$def = array('{1,2,3}', '{lat1,lat2,lat3}', '{lon1,lon2,lon3}'); 

$new = array(); 
$i=0; 
foreach($def as $value) { 
    $list = explode(",", str_replace(array("{", "}"), null, $value)); 
    $k=0; 
    foreach($list as $item) { 
     $new[$k][$i] = $item; 
     $k++; 
    } 
    $i++; 
} 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => 1 
      [1] => lat1 
      [2] => lon1 
     ) 

    [1] => Array 
     (
      [0] => 2 
      [1] => lat2 
      [2] => lon2 
     ) 

    [2] => Array 
     (
      [0] => 3 
      [1] => lat3 
      [2] => lon3 
     ) 

) 
+0

嗨,謝謝,我正在努力。 – mgm

+0

@mag我用一個例子更新了我的答案 – Peon

+0

我正在閱讀它,謝謝。我已經解決了在創建表格時使用創建類型的想法。我仍然需要弄清楚爲什麼像array_agg(row(latitude,longitude):: coordinate)會返回類似於{「(lat1,lon2)」}而不是{(lat1,lon2)}的東西。我將座標定義爲創建類型座標(緯度真實,經度真實);想法? :) – mgm

1

可以使用查詢(更改數據類型後)如下:

select 
array_cat 
(
    array_cat 
    (
     array [ [ objects[1], latitutes[1], longitudes[1] ] ] 
    , array [ objects[2], latitutes[2], longitudes[2] ] 
    ) 
, array [ objects[3], latitutes[3], longitudes[3] ] 
) 
from examplary_table ; 

其給出了這樣的結果:

{{1,111,121},{2,112,122},{3,113,123}} 

對於測試目的:

with examplary_table as 
(
    select * from 
    (
    values 
     (
      '{1,2,3}'::int[] 
     , '{111,112,113}'::int[] 
     , '{121,122,123}'::int[] 
     ) 
    ) a (objects, latitutes, longitudes) 
) 
select 
array_cat 
(
    array_cat 
    (
     array [ [ objects[1], latitutes[1], longitudes[1] ] ] 
    , array [ objects[2], latitutes[2], longitudes[2] ] 
    ) 
, array [ objects[3], latitutes[3], longitudes[3] ] 
) 
from examplary_table ;