PostgreSQLで位置情報
PostGISがメジャー(なのか?)だけど、使わないやり方。
PostgreSQLのデータ型に、平面における座標点を扱う『point型』というのがある。
[使用例]
テーブル作成
===== # create table location_data (id integer, location point); =====
データ挿入
x座標が100、y座標が200の場合
===== # insert into location_data (id, location) values(1, point(100, 200)); =====
抽出すると
===== # select * from location_data; id | location ----+----------- 1 | (100,200) 2 | (150,100) 3 | (200,200) (3 rows) =====
x座標、y座標を別々に取り出すには
===== # select location[0] as x, location[1] as y from location_data; x | y -----+----- 100 | 200 150 | 100 200 | 200 (3 rows) =====
絞り込み その1
2つのpointを対角とした長方形に含まれる範囲
===== # select * from location_data \ where location @ box(point(150, 100),point(200,300)); id | location ----+----------- 2 | (150,100) 3 | (200,200) (2 rows) =====
絞り込み その2
あるpointを中心とする半径rの円に含まれる範囲
===== # select * from location_data where location @ circle(point(200, 200),100); id | location ----+----------- 1 | (100,200) 3 | (200,200) (2 rows) =====
ソート
===== # select * from location_data where location @ circle(point(200, 200),100) order by location <-> point(200,200); id | location ----+----------- 3 | (200,200) 1 | (100,200) (2 rows) =====
とりあえず、ざっとこんな感じ。
インデックスの張り方は次の機会に。