2014-11-25 44 views
0

我正在使用Ruby(而不是Rails)和PostgeSQL,並且一直在敲打我的頭幾個小時,試圖弄清楚如何在知道列和列時指定字段的值你試圖交叉引用的行。查詢具有已知列和行的特定單元格

我曾嘗試以下:

一個包含城市和連接距離,類似於數據庫:

Cities city1 city2 city3 city4 
city1 0 17 13  6 
city2 17 0 7  15 
city3   . . . 
city4   . . . 

,我曾嘗試用下面的代碼打轉轉:

array.each { |city| #array being the array containing the sorted cities 
    from_city = city 

    query { |row| 
     #row is a hash containing each city as key and distance as val 
     #first row: {"Cities"=>"city1", "city1"=>"0", "city2"=>"17",... 
     #I have tried doing a row.each and grabbing the value of the specified city key, 
          but that doesn't work.. 

    } 
} 

是有更好的方法去做這件事?基本上所有我需要知道的是,當我知道我想要使用的兩個城市時,如何獲得距離值,並將其分配給變量distance

+0

你用什麼來連接數據庫?我強烈建議尋找[Sequel](http://sequel.jeremyevans.net/)寶石。它非常強大和靈活。而且,爲了幫助你的術語,數據庫有行和*字段*,而不是單元格。 – 2014-11-25 07:01:24

+0

我正在使用pg gem。目前爲止我的工作很好,但我只是堅持這一點。仍然是Ruby和數據庫的新手..:/ – Luminusss 2014-11-25 07:06:11

+0

假設你知道'to_city',解決方案就像'row [to_city]'一樣簡單。 – mudasobwa 2014-11-25 08:16:51

回答

0

我會改變你的數據庫模式(SQL數據庫是不是真的旨在通過列訪問工作,並添加新的一列,每次你添加一個城市真的很痛做):

origin | destination | distance 
city1 | city2  | 17 
... More rows ... 

那查找2個城市之間的距離只是:

conn.exec_params('SELECT distance from cities where origin = $1 and destination = $2', [city1, city2]) 

這將返回1行與1列,這是兩者之間的距離。

或者,如果您的數據集很小並且變化不大,那麼將數據作爲文件存儲並在啓動時將其加載到內存中沒有任何問題。取決於你的用例。另外,如果你要做大量的幾何計算,PostGIS可能是你想要的。

相關問題