2013-10-01 151 views
1

我有三個表 - 商店,土豆和番茄(番茄表看起來像馬鈴薯表)。在馬鈴薯桌上的id是商店的id - 所以這家商店的馬鈴薯的價格。從多個表中獲取數據

+----+-------+-----------+ 
|   potato   | 
+----+-------+-----------+ 
| id | price | date_time | 
+----+-------+-----------+ 

+----+-----+-----+------+------+ 
|    shop    | 
+----+-----+-----+------+------+ 
| id | lat | lng | name | geom | 
+----+-----+-----+------+------+ 

我想要做的是選擇所有距離某個位置最多10公里的商店,以及番茄和土豆價格。

現在,我有這個疑問,可以選擇店,土豆價格

SELECT 
    shop.lat, 
    shop.lng, 
    shop.id, 
    potato.date_time AS potato_date, 
    potato.price as potato_price 
FROM 
    shop, 
    potato 
WHERE 
    potato.id = shop.id AND 
    ST_DWithin(
     ST_GeomFromText('POINT(xx.xxxxxx yy.yyyyyy)',4326), 
     shop.geom, 
     10*1000, 
     true 
    ); 

一起,但我想也得到在那家商店西紅柿的價格。它怎麼能做到?

回答

3

使用LEFT JOIN

SELECT 
    shop.lat 
    , shop.lng 
    , shop.id 
    , potato.date_time AS potato_date 
    , potato.price as potato_price 
    , tomato.date_time as tomato_date 
    , tomato.price as tomato_price 
FROM shop 
LEFT JOIN potato on potato.ID = shop.ID 
LEFT JOIN tomato on tomato.ID = shop.ID 
WHERE ST_DWithin(ST_GeomFromText('POINT(xx.xxxxxx yy.yyyyyy)',4326), shop.geom,10*1000, true); 

如果每個商店出售的西紅柿和土豆,你可以使用內部連接。