使用mysql php运行基于另一个查询的查询

时间:2012-09-26 22:02:29

标签: php mysql subquery implode

下面的代码搜索我的mysql数据库,并返回邮政编码,如IG6,RM11,RM8,RM4,RM2,RM6,RM7,RM1,RM5以及使用存储过程的距离。 (一切都好)

问题:通过这些结果,我想在同一个数据库中搜索可能包含这些邮政编码的作业信息的另一个表(可能使用LIKE)。

让这项工作最好的方法是什么?我尝试过很多例子(implodearrays等) 与数据库的一个连接是否正确?我如何查询变量,因为它返回2列,邮政编码和距离。我应该分成一个数组(如何?)

结束产品:HGV司机RM5,清洁RM5,老师RM5

SELECT title FROM jobinfo WHERE location IN results from other query);

 <?php
    include ("conn.php");
    $first="RM5";

    $result = mysql_query("select outcode, GetDistance(Lat, Lon, (SELECT Lat from postcodes where outcode = '$first' limit 1),(SELECT Lon from postcodes where outcode = '$first' limit 1)) as Distance from postcodes having Distance < 3 order by Distance DESC;");
    while($row = mysql_fetch_array($result))
    {
        echo  ($row['outcode']) ;
    } 
    // This returns postcodes

    $resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($results[outcode]) ");
    while($row = mysql_fetch_array($resultb))
    {
        echo  ($row['title']) ;
    }
    mysql_close($con);
?> 

请帮助.....任何参考加入表都需要完整的解释,因为到目前为止都没有帮助!

2 个答案:

答案 0 :(得分:1)

首先将输出准备到子句中:

在第一个while循环中:

while($row = mysql_fetch_array($result))
 {
    $array[] = $row['outcode'] ;
 } 

然后为IN子句准备数组:

foreach ($array as $a) {$clause.= "'$a',";}
$clause=substr($clause,0,-1)

最后使用IN语句的子句:

$resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($clause) "

=====编辑=== LIKE语句

对于喜欢..你需要多个类似的声明OR .. Using SQL LIKE and IN together

将prepare子句代码更改为:

foreach ($array as $a) {$clause.= " location LIKE '%$a%' OR";}
$clause=substr($clause,0,-3)

并且sql变为:

$resultb = mysql_query("SELECT title FROM jobinfo WHERE $clause ");

当然你会想要添加一些错误检查......想想可能的注射。

答案 1 :(得分:0)

我认为你正在尝试做这样的回答MySQL LIKE IN()?

另外,请使用参数化查询How can I prevent SQL injection in PHP?