mysql查询使用另一个查询的数组结果

时间:2012-06-17 19:37:56

标签: php mysql arrays mysqli

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

$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中选择所有内容?

1 个答案:

答案 0 :(得分: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
相关问题