我试图学习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
答案 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