简体   繁体   中英

mysql query using array result of another query

I have a simple query that finds cities that are within a certain distance of a given latitude and longitude.

$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";

And then displays the results:

$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 />";
}

What I want to do is instead of echoing the results, take that array and do another query that has information about those cities in another table and then echo the results. Is there a way I can do this w/o having to do 10 subqueries:

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

How do I say "take the array of cities and states from table1, and select everything from table2 using that array?

A simple INNER JOIN between the two will do the job:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM