sql选择过滤器和未过滤器

时间:2015-05-21 12:00:43

标签: php mysql sql

$query = "SELECT id, 
                user, 
                need, 
                offer, 
                details 
         FROM list 
         WHERE need=$sneed 
            and offer=$soffer 
         ORDER BY id DESC";

这就是我想要的:

$sneed = 1;
$soffer = 2;

将显示所有需要1且提供2的记录,这样就可以了。

$sneed = 1;
$soffer = NULL;

将显示有需要的所有记录1,这不是发生的事情,我怎么能实现呢?

$sneed = NULL;
$soffer = NULL;

将显示所有记录。也没发生。 这可能吗?

3 个答案:

答案 0 :(得分:1)

$where="";

if($sneed && $soffer)
{
    $where="where need=$sneed and offer=$soffer";
}else if($sneed){
    $where="where need=$sneed";
}
}else if($soffer){
    $where="where offer=$soffer";
}

$query = "SELECT id, user, need, offer, details FROM list $where ORDER BY id DESC";

答案 1 :(得分:0)

如果您不关心性能,只需修复WHERE

中的逻辑
WHERE (need = $sneed OR $sneed IS NULL) and
      (offer = $soffer OR $soffer IS NULL)

如果你关心性能(特别是在needoffer上使用索引),那么只使用你需要的子句在应用程序中构造正确的查询。

答案 2 :(得分:0)

你可以添加许多参数,不仅仅是2

 $query = "SELECT id, user, need, offer, details FROM list WHERE 1 = 1 ";

if($sneed){
  $query .= " and need=".$sneed;
}

if($soffer){
  $query .= " and offer=".$soffer;
}

if($anotheroffer){
      $query .= " and anotheroffer=".$anotheroffer;
}

注意:不要忘记转义字符串mysql_real_escape_string()以避免sql注入。