dqw7121 2012-06-17 19:37
浏览 127
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • dsfdgdsfd23212 2012-06-17 19:40
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?