sql - 从多个表中获取数据

标签 sql postgresql select postgis

我有三张 table - shop、potato 和 tomato(tomato table 看起来像 potato table )。土 bean 表中的 id 实际上是商店的 id - 所以那家商店的土 bean 的价格。

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

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

我想做的是选择距离某个位置最多 10 公里的所有商店,以及番茄和土 bean 的价格。

现在,我有这个查询,它可以选择商店以及土 bean 价格

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

但我还想知道那家商店里西红柿的价格。怎么做到的?

最佳答案

使用左连接

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

如果每个商店都出售西红柿和土 bean ,您可以使用内部联接。

关于sql - 从多个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126048/

相关文章:

sql - 使用子查询时查询失败

javascript - html select list - 获取显示的文本值

mysql - 将 MySQL 迁移到 DB2

sql - 当行值非零时获取列表聚合中的列名称

php - MySQL 查询返回的结果比预期的要多

sql - 按季度 SQL 查询的聚合结果

postgresql - 如何在构建 Docker 镜像时恢复 Postgresdump?

regex - 如何预编译正则表达式?

sql - 按位置、客户名称和月份对查询结果进行分组

sql - 使用 SELECT UNION 并从一张表中返回两列的输出