mysql中的if子句选择

时间:2019-02-19 06:25:28

标签: php jquery mysql select

我的完整查询是:

$sql = "SELECT vehicle_id,  fuel_type, gearbox_type, door_type, engine_package_name, FORMAT(engine_cap, 1)engine_cap, engine_power, FORMAT(fuel_cons, 1)fuel_cons, FORMAT(std_price, 0)std_price 
FROM vehicle 
WHERE model_id = '$model_id' 
AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4') AND gearbox_type IN( '$gearbox_type1', '$gearbox_type2', '$gearbox_type3', '$gearbox_type4') AND door_type IN ('$door_type1', '$door_type2', '$door_type3', '$door_type4')" ;

如果$fuel_type1等于零,我想跳过下面显示的查询部分。

AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4') 

我尝试过

$sql = "SELECT vehicle_id,  fuel_type, gearbox_type, door_type, engine_package_name, FORMAT(engine_cap, 1)engine_cap, engine_power, FORMAT(fuel_cons, 1)fuel_cons, FORMAT(std_price, 0)std_price 
FROM vehicle 
WHERE model_id = '$model_id' ";

if($fuel_type1 != 0) 
{ 
    $sql += “ AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4')”;
}

没用。

我也尝试过

$sql = "SELECT vehicle_id, fuel_type, gearbox_type, door_type, engine_package_name, FORMAT(engine_cap, 1)engine_cap, engine_power, FORMAT(fuel_cons, 1)fuel_cons, FORMAT(std_price, 0)std_price 
FROM vehicle 
WHERE model_id='$model_id’ 
AND IF($fuel_type1 <> 0,'fuel_type','0') IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4’)";

没有用:((

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

问题在连接过程中

在PHP中,应该使用.来连接非+符号

if($fuel_type1 != 0) 
{ 
    $sql .= “ AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4')”;
}