简体   繁体   English

MySQL存储过程与if语句

[英]MySQL stored procedure with if statement

I have following stored procedure in MySQL 我在MySQL中有以下存储过程

SELECT *
    FROM rewards
        LEFT JOIN tasks
        ON tasks.id = rewards.task_id
        AND rewards.received_at = received_Date
    WHERE tasks.kid_id = kid_Id
    ORDER BY tasks.id ASC;

The stored procedure has 2 (IN) inputs, kid_Id (integer) and received_Date (date), and it works fine. 该存储的过程有2个(IN)输入, kid_Id (整数)和received_Date (日期),并能正常工作。

Question: What I want is if the received_Date is NULL then I want to view all dates, is that possible? 问题:我想要的是,如果received_DateNULL那么我想查看所有日期,这可能吗?

Say in other words: 换句话说:

the AND rewards.received_at = received_Date should only work if I pass received_Date otherwise return all dates. AND rewards.received_at = received_Date如果我通过应只工作received_Date否则返回所有日期。

Try this. 尝试这个。 Use OR operator in where clause to get all the rows if received_Date is null 如果received_Date is null则在where clause使用OR运算符获取所有行

SELECT *
    FROM rewards
        LEFT JOIN tasks
        ON tasks.id = rewards.task_id
                WHERE tasks.kid_id = kid_Id 
                AND (rewards.received_at = received_Date or received_Date = 0) 
    ORDER BY tasks.id ASC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM