1

我有一个简单的查询,可以找到在给定纬度和经度一定距离内的城市。

$query = "SELECT city,state,((ACOS(SIN($lat * PI() / 180) * SIN(lat * PI() / 180) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * COS(($lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM us_cities WHERE population<>'' HAVING distance<=30 ORDER BY distance ASC limit 1, 10";

然后显示结果:

$rows = mysqli_num_rows($result);           
for ($i = 0; $i < $rows; ++$i) {            
$row = mysqli_fetch_assoc($result);
echo $i+1;
echo $row['city'] . "<br />";
echo $row['state'] . "<br />";
}

我想要做的不是回显结果,而是采用该数组并执行另一个查询,该查询在另一个表中包含有关这些城市的信息,然后回显结果。有没有办法我可以做到这一点而不必做 10 个子查询:

Select * FROM table2 WHERE city=city AND state=state;

我怎么说“从 table1 中获取城市和州的数组,并使用该数组从 table2 中选择所有内容?

4

1 回答 1

4

两者之间的简单INNER JOIN将完成这项工作:

SELECT 
  /* Need to add table name or alias in select list since both tables have these cols */
  us_cities.city,
  us_cities.state,
  ((ACOS(SIN($lat * PI() / 180) * SIN(lat * PI() / 180) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * COS(($lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance 
FROM
   us_cities
   /* Join on city and state */
   INNER JOIN table2 
      ON us_cities.city = table2.cities 
      AND us_cities.state = table2.state
WHERE population <>''
HAVING distance<=30
ORDER BY distance ASC 
limit 1, 10
于 2012-06-17T19:40:59.833 回答