如果statement为1则运行特定的SQL语句

时间:2015-10-08 08:03:30

标签: mysql if-statement stored-procedures

我试图学习MySQL存储过程,并且我陷入了一个If ..那么重要。 我试图弄清楚如何显示列对IF结果的影响。

这是我的代码,希望您了解我想要做的事情,我的问题出在" ..."和" ..." :

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_helloworld`()
BEGIN

    SELECT
        ...
        IF pt.is_part_payment = 1 THEN
            pp.due_date AS due_date,
            pp.amount AS amount
        ELSE
            o.due_date AS due_date,
            o.amount AS amount
        END IF;
        ...
    FROM
        orders o
        INNER JOIN payment_types pt ON pt.id = o.payment_type_id 
        INNER JOIN part_payments pp ON pp.order_id = o.order_id
    WHERE
        o.active = 1
END

1 个答案:

答案 0 :(得分:0)

如您所见,您不能在SQL查询中放置if语句。但是,您可以使用case表达式,但是您必须为每个要单独查询的字段执行此操作:

SELECT
    ...
    CASE pt.is_part_payment WHEN 1 THEN pp.due_date ELSE o.due_date END
        AS due_date,
    CASE pt.is_part_payment WHEN 1 THEN pp.amount ELSE o.amount END AS amount,
...
FROM
    orders o
    INNER JOIN payment_types pt ON pt.id = o.payment_type_id 
    INNER JOIN part_payments pp ON pp.order_id = o.order_id
WHERE
    o.active = 1