mysql选择if变量的设置位置

时间:2013-10-03 07:57:49

标签: php mysql sql

我有两张桌子:

  • 销售
  • sales_sizes

我想查询受变量$ gender,$ category和$ brand约束的sales_sizes。

如果设置了各个变量,如何设置where语句,如果未设置,则不在查询中包含它们?

[括号中的伪代码]

SELECT size, country
FROM `sales_sizes` WHERE sale_id IN (
    SELECT sale_id
    FROM `sales`
    WHERE [gender = $gender if $gender isset]
    AND [category = $category if $category isset]
    AND [brand = $brand if $brand isset]

) 

2 个答案:

答案 0 :(得分:1)

您可以将变量收集到数组中,然后像这样处理它:

$gender   = 'f';
$category = null;
$brand    = 'foo';

$rgCondition = ['gender'=>$gender, 'category'=>$category, 'brand'=>$brand];
$rgCondition = array_filter($rgCondition, function($x)
{
   //strip null-ed values:
   return isset($x);
});
$rgWhere     = [];

foreach($rgCondition as $sField=>$mValue)
{
   $rgWhere[] = '`'.$sField.'` = "'.$mValue.'"';   
}
$sWhere = count($rgWhere)?' WHERE '.join(' && ', $rgWhere):'';
//var_dump($sWhere);

- 我跳过字符串转义,但不要忘记它。

答案 1 :(得分:0)

使用CASE语句 更新:以前的语法(由少数人指出)不起作用。您可以按如下方式使用CASE:

SELECT size, country
FROM `sales_sizes` WHERE sale_id IN (
    SELECT sale_id
    FROM `sales`
    WHERE [gender = $gender if $gender isset]
    AND [category = $category if $category isset]
    AND [brand = $brand if $brand isset]

)

WHERE gender
  CASE WHEN gender ($gender) = isset THEN 
    $gender 
  ELSE
    $gender='NULL'
  END