doubingqi5829 2012-10-31 20:26
浏览 35
已采纳

基于先前精炼的MySQL查询从MySQL中选择

really didn't want to ask this because I'm sure its simple but:

I have a database of users which include fields for postcode(zipcode) and Date of Birth.

A visitor can search for a user by age and distance to their own location. To do this, I have to SELECT all users, then calculate their age, and then calculate their distance, something like this:

$result = queryMysql("SELECT user FROM table WHERE user !='$user' ORDER BY joindate DESC ");
$num = mysql_num_rows($result);

for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;

$query = "SELECT * FROM table WHERE user='$row[0]'";
$res=mysql_query($query);
$users=mysql_fetch_assoc($res);

//Get Date of Birth and Calculate Age
$dob = $users['age'];
$age = ...

//Get Profile's Postcode and Calculate Distance 
$profilepc = $views['postcode'];
$distance = ...

if(($distance <200) AND ($age >18 AND <30)) {

}

So far, no problem. However I then want to run another query (for pagination) selecting ONLY those users who fit within the age and distance parameters set by the visitor, which i can echo in the above IF statement, but i don't know how to include in a new Query.

So, HOW do I place the results of the first query into something(an array?), and then user the user_id's (which are unique) from that first query to only select the required users for my pagination? Something like:

SELECT * FROM $table WHERE user_id=(filtered user_id's) ORDER BY joindate DESC 

I hope that makes sense. Thanks

  • 写回答

3条回答 默认 最新

  • dpl9717 2012-10-31 20:32
    关注

    You can use a subquery for your IN clause, or if you already have a PHP array of IDs:

    // assuming your array of IDs is
    $user_ids = array(1, 2, 3, 4);
    
    // use implode() to create a comma separated list for use in your IN clause
    $query = "SELECT * FROM {$table}
    WHERE user_id IN (" . implode(',', $user_ids) . ") 
    ORDER BY joindate DESC;"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b