在MySQL中使用具有复杂逻辑的动态查询

时间:2014-04-20 07:42:02

标签: mysql dynamic

我想创建一个包含4个参数的过程:p_customer_idp_plant_idp_order_monthp_order_year然后使用参数值执行select语句过滤器。以下是逻辑/伪代码:

Set @customer_id = p_customer_id;
Set @plant_id = p_plant_id;
Set @order_month = p_order_month;
Set @order_year = p_order_year;


If all four parameters are null
    then select * from table_1;

If the customer_id is not null
    then select * from table_1 where customer=customer_id;

If plant_id is not null then 
    if customer_id is null then
        select * from table_1 where plant_id  = @plant_id
    if customer_id is not null then 
         select * from table_1 when plant_id = @plant_id 
                               and customer_id = @customer_id;

p_order_monthp_order_year继续。如果参数值为null,则该过程将在执行select from table_1时从过滤器中排除参数。

因此,当所有参数都有效时,程序将执行

select * from table_1 
where customer_id = @customer_id
plant_id = @plant_id
order_month = @order_month
order_year = @order_year

我考虑使用动态stmt和execute using @customer_id, @plant_id, @order_month, @order_year,但不确定我是否在正确的轨道上。

任何建议都将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:1)

以下陈述符合您的所有逻辑:

select * from table_1 where (ifnull(@customer_id,-1)=-1 or customer_id = @customer_id) and (ifnull(@plant_id,-1)=-1 or plant_id = @plant_id) and (ifnull(@order_month,-1)=-1 or order_month = @order_month) and (ifnull(@order_year,-1)=-1 or order_year = @order_year)

或者简单地说:

select * from table_1 where (@customer_id is null or customer_id = @customer_id) and (@plant_id is null or plant_id = @plant_id) and (@order_month is null or order_month = @order_month) and (@order_year is null or order_year = @order_year)

还尝试用列名替换*。这是更好的做法。