将部分查询合并为一个的语法

时间:2014-05-20 09:52:48

标签: php mysql

我想基于另一个创建一个新查询。

示例:

    $query = "SELECT * FROM `table2` WHERE `field2` > 0 AND (`field3` LIKE '%".$keyword%."%' OR `field4` LIKE '%".$keyword."%' ** insert new parameters from another query here **  ) AND `field5` <= 0\"';

我在下面尝试过但没有工作。不知道我是否正确。

   $keyword = $_POST['keyword'];
$query = "SELECT * FROM `table1` WHERE `field` LIKE '%$keyword%'";
if ($result = $con->query($query)) {
    $new_query = '\"SELECT * FROM `table2` WHERE `field2` > 0 AND (`field3` LIKE \'%\".$keyword%.\"%\' OR `field4` LIKE \'%\".$keyword.\"%\'';
    while ($row = mysqli_fetch_assoc($result)) {
        $keyword2 = $row['something'];
        $new_query .= " OR `field2` LIKE '%" . $keyword2 . "%' OR `field4 LIKE '%" . $keyword2 . "%'";
    }
    $new_query .= ') AND `field5` <= 0\"';
}

if ($result = $con->query($new_query)){
    .........etc
}

感谢有人可以提供帮助!!

1 个答案:

答案 0 :(得分:1)

试试这个

$new_query = "SELECT * FROM table2 WHERE field2 > 0 AND (field3 LIKE '%$keyword%' OR field4 LIKE '%$keyword%' ";
...
$new_query .= " OR `field2` LIKE '%$keyword2%' OR `field4 LIKE '%$keyword2%'";
...
$new_query .= ') AND `field5` <= 0';
var_dump($new_query); // have a look at the query you have created