从表中选择缺少某些WHERE条件的表

时间:2015-03-14 01:26:33

标签: php mysql sql sorting conditional-statements

我有以下sql请求

        if(isset($_GET['room'])) {

            if($_GET['status'] == 'all' && $_GET['room'] == 'all'){
                $stmt = $pdo->prepare("SELECT DISTINCT flatnetto FROM flat ORDER BY flatnetto");
                $stmt->execute(array($_GET['room'], $_GET['status']));
            }else if($_GET['status'] == 'all'){
                $stmt = $pdo->prepare("SELECT DISTINCT flatnetto FROM flat WHERE kk = ? ORDER BY flatnetto");
                $stmt->execute(array($_GET['room']));
            }else if($_GET['room'] == 'all'){
                $stmt = $pdo->prepare("SELECT DISTINCT flatnetto FROM flat WHERE sold = ? ORDER BY flatnetto");
                $stmt->execute(array($_GET['status']));
            }else{
                $stmt = $pdo->prepare("SELECT DISTINCT flatnetto FROM flat WHERE kk = ? AND sold = ? ORDER BY flatnetto");
                $stmt->execute(array($_GET['room'], $_GET['status']));
            }               

            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }

可以从上面的代码中只生成一个sql请求吗?我的意思是,可以只提出一个请求

    $stmt = $pdo->prepare("SELECT DISTINCT flatnetto FROM flat WHERE kk = ? AND sold = ? ORDER BY flatnetto");

但条件" kk"和"出售"可能存在也可能不存在(将具有不可靠的"所有"值)。例如,如果" kk"不存在只是忽略它并继续只选择条件"出售"。

上面的代码正在运行,但定义所有可能的选项非常烦人。


状态可以包含值(已售出,已保留,全部)

房间可以有值(1kk,2kk,3kk,All)

价值"所有"意味着,例如我对2kk房间感兴趣,无论是否"出售"或"保留"告诉我他们所有人。

更新的问题。

正如下面的回答所写,可以发出一个sql请求。但问题仍然存在,因为我们只是移动了可能的选项定义"到SQL查询但我还是要定义所有可能的选项。我无法想象如何定义所有可能的选项,如果我们不只有两个输入,但例如"房间,状态,价格1,价格2,楼层,大小..."并且他们所有人都有自己的价值,但也有价值所有"。在这种情况下,我们必须从所有可能的变化中定义所有可能的选项(在这种情况下,超过20种可能的变化)。我认为这不是它在大型项目中如何运作的方式。

2 个答案:

答案 0 :(得分:0)

考虑关于所有可能性的详尽的联合查询。根据选择参数,只输出一行查询:

$stmt = $pdo->prepare("SELECT DISTINCT flatnetto FROM flat WHERE kk = :kk 
AND sold = :sold AND NOT kk = 'all' AND NOT sold = 'all ORDER BY flatnetto
UNION SELECT DISTINCT flatnetto FROM flat WHERE kk = 'all' AND sold = :sold
ORDER BY flatnetto
UNION SELECT DISTINCT flatnetto FROM flat WHERE kk = :kk AND sold = 'all'
ORDER BY flatnetto
UNION SELECT DISTINCT flatnetto FROM flat WHERE kk = 'all' AND sold = 'all' 
ORDER BY flatnetto");
$stmt->execute(array(':kk' => $_GET['room'], ':sold' => $_GET['status']));

答案 1 :(得分:0)

您可以使用以下代码生成SQL查询

$param=Array();

## associate query parameters to sql column
$keys=Array("room" => "kk", "status" => "sold");

## generate parameter list
foreach ($keys as $k=>$v)
if (isset($_GET[$k])&&($_GET[$k]!='all'))
   $param[$v]=$_GET[$k];

## generate query
$query="SELECT DISTINCT flatnetto FROM flat WHERE ".
    implode(" = ? AND ", array_keys($param)).
    (count($param) ? " = ?" : "1")
    ." ORDER BY flatnetto";

## execute
$stmt = $pdo->prepare($query);
$stmt->execute($param);