如何将3个mysql查询组合在一起?

时间:2012-09-02 11:38:56

标签: php mysql

我有3种不同类型的查询来检索同一页面中的数据。我将如何完全结合?以下是查询:

<?php
$sql = "SELECT * FROM general WHERE ((day1sql >= now()))";
if($_GET!=""){
$mydate = mysql_real_escape_string($_GET['datepicker']);
if($mydate!=""){    
$sql = "SELECT * FROM general WHERE ((day1 = '$mydate'))";  
}       
}
if($_GET!=""){
$city1 = mysql_real_escape_string($_GET['cityText']);
if($city1!=""){ 
$sql = "SELECT * FROM general WHERE (city = $city1))";  
}       
}

datepicker是一个日历,用户可以根据日期获取数据。并且有一个下拉菜单,用户可以选择城市名称。前两个查询工作正常。我很困惑如何整合第三个查询?

2 个答案:

答案 0 :(得分:2)

您可以使用logical OR operator组合过滤条件:

SELECT * FROM general WHERE day1sql >= now() OR day1 = '$mydate' OR city = '$city1'

答案 1 :(得分:0)

这样的事可能有用:

sql = "SELECT * FROM general WHERE (day1sql >= now())";

if(isset($_GET['datepicker'])){
    $mydate = mysql_real_escape_string($_GET['datepicker']);
    $sql .= " AND (day1 = '$mydate')";         
}
if(isset($_GET['cityText'])){
    $city1 = mysql_real_escape_string($_GET['cityText']);
    $sql .= " AND (city = $city1)";  
}       

// execute $sql

我们正在使用AND条件附加sql。我相信你正在做的事情。