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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制