gpt4 book ai didi

mysql - mysql : Add if condition in where statement?

转载 作者:行者123 更新时间:2023-11-29 07:03:51 25 4
gpt4 key购买 nike

我想选择所有客户或来自同一 SP 的一名客户。目前我们正在维护两个 SP 来获取这些详细信息:

即要获得所有客户:

select id, name from customers

并获得一位客户:

select id, name from customers
where id=id_from_input

为了使它们变得通用,我想到将 id_from_input 传递为 null 来获取所有客户。我尝试了多种方法在我的 sql 中创建一个适用于该计划的条件 where 语句,但没有任何效果。例如:

select id, name from customers
where if(id_from_input <> null) id=id_from_input; end if

给我语法错误。

如何创建一个 where 子句,当 id_from_input 为 null 时返回所有行,否则返回匹配行?

最佳答案

表达式x <> null从来都不是真的;您只能使用 is null ,或is not null ,测试是否为空。纠正你的尝试给出:

select id, name from customers
where id_from_input is null or id = id_from_input

或者想要更简洁的东西(恕我直言,优雅):

select id, name from customers
where id = coalesce(id_from_input, id)

关于mysql - mysql : Add if condition in where statement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42479170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com