如何使用函数连接两个MySQL表

时间:2010-06-25 17:31:31

标签: mysql select join

我需要一些帮助加入两张桌子。我有:

my_type_table,其中包含以下列:

  • type(VARCHAR)
  • 纬度(十进制)
  • 经度(十进制)

...和neighborhood_shapes,其中包含以下列:

  • 邻里(VARCHAR)
  • neighborhood_polygons(geometry)

我有一个名为myWithin的函数,它检查纬度和经度,看它们是否在邻域多边形中。它以lat long和邻域形状为参数。如果该点不在多边形中,则myWithin函数返回0;如果该点在多边形内,则返回1。

我可以按如下方式制作一个选择语句:

SELECT type, latitude, longitude, 'Newport' AS neighborhood
  FROM my_type_table
WHERE myWithin(POINTFROMTEXT( CONCAT( 'POINT(', latitude, ' ', longitude, ')' ) ) , 
               (SELECT neighborhood_shapes.neighborhood_polygons
                  FROM neighborhood_shapes
                 WHERE neighborhood_shapes.neighborhoods = 'Newport')) = 1

此选择的结果例如:

type  |  latitude | longitude | neighborhood
---------------------------------------------
small |  30.3030  | -70.7070  | Newport

我的问题是我有很多社区。我不想每次都输入邻居。有没有办法删除“纽波特”?基本上,我希望函数在每个点上运行并给出类型,纬度,经度以及该点所在的邻域?

我可以复制上面的选择并使用UNION ALL加入select语句,但是在每个邻居的名字中键入一个噩梦。必须有更好的方法。

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

我当然没有对此进行测试......但似乎它可以像这样进行重组:

SELECT t.type, t.latitude, t.longitude, s.neighborhood 
  FROM my_type_table t, neighborhood_shapes s
WHERE myWithin(POINTFROMTEXT( CONCAT( 'POINT(', t.latitude, ' ', t.longitude, ')' ) ) ,               s.neighborhood_shapes.neighborhood_polygons ) = 1

答案 1 :(得分:1)

你试过......

SELECT DISTINCT type,
                latitude,
                longitude,
                ns.neighborhoods AS neighborhood
    FROM my_type_table,
         neighborhood_shapes ns
    WHERE myWithin(POINTFROMTEXT( CONCAT( 'POINT(', latitude, ' ', longitude, ')' ) ) , 
                   (SELECT neighborhood_shapes.neighborhood_polygons
                        FROM  neighborhood_shapes
                        WHERE neighborhood_shapes.neighborhoods = ns.neighborhoods)) = 1

答案 2 :(得分:0)

function getNeighborhood ($neighborhood) {


$sql = "SELECT type, latitude, longitude, 'Newport' AS neighborhood
  FROM my_type_table
WHERE myWithin(POINTFROMTEXT( CONCAT( 'POINT(', latitude, ' ', longitude, ')' ) ) , 
               (SELECT neighborhood_shapes.neighborhood_polygons
                  FROM neighborhood_shapes
                 WHERE neighborhood_shapes.neighborhoods = $neighborhood)) = 1";

$result = /**  Do Query Here**/

return $result;
}