从多个表中获取数据

时间:2013-10-01 21:13:39

标签: sql postgresql select postgis

我有三张桌子 - 商店,土豆和番茄(番茄桌看起来像土豆桌)。马铃薯桌上的身份确实是商店的身份 - 所以那个商店的马铃薯的价格。

+----+-------+-----------+
|         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
    );

但是我想得到那家商店的番茄价格。怎么可能呢?

1 个答案:

答案 0 :(得分: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 );

如果每家商店都出售西红柿和土豆,你可以使用内部连接。