简体   繁体   English

在 mysql select 语句中使用条件 where 子句

[英]using conditional where clauses in mysql select statement

There is a stored procedure sp_select_from_persons in MySql. MySql 中有一个存储过程sp_select_from_persons And there are 3 parameters inside this procedure.这个过程中有3个参数。 age, class, group . age, class, group These parameter values can be -1 or another value.这些参数值可以是 -1 或其他值。 And these parameters will be used in where clause.这些参数将在where子句中使用。
Now I want to write where clause like that, if any value of these parameter is another than -1 then append them into where clause.现在我想像这样编写 where 子句,如果这些参数的任何值不是-1,则将它们附加到where子句中。 For example:例如:
if age = -1, class = 7 and group = 5 then select query will be:如果年龄 = -1,班级 = 7 且组 = 5,则选择查询将是:

SELECT * FROM persons p WHERE p.class = class AND p.group = group;  

or if age = 25, class = -1 and group = -1 then:或者,如果年龄 = 25,班级 = -1 且组 = -1,则:

SELECT * FROM persons p WHERE p.age = 25;

and etc.等等。

I don't want to use emnedded IF statements like below:我不想使用像下面这样的嵌入式 IF 语句:

IF age > 0 THEN 
  IF class > 0 THEN
     IF group > 0 THEN
     SELECT * FROM persons p WHERE p.age = age AND p.class = class AND p.group = group;
     END IF
     ELSE ....... etc

Is there a better way to do this?有一个更好的方法吗?

This is a single line query.... Try This这是一个单行查询....试试这个

SELECT * FROM persons p 
WHERE p.age = case when age = -1 then p.age else age end
and p.class = case when class = -1 then p.class else class end
and p.group = case when group = -1 then p.group  else group end

Something like this also worked for me:像这样的事情也对我有用:

create procedure sp_my_proc(in p1 varchar(10), in p2 int)
    begin
        SELECT col1, col2 from my_table
         where if(p1 is null or length(trim(p1)) = 0, true, col1 = p1)
           and if(p2 = 0, true, col2 = p2);
    end

My requirement is that the stored proc is being called from a Java/SpringFramework-based back-end where passing null values to stored proc invocation is not accepted so values are set to empty string.我的要求是从基于Java/SpringFramework-based后端调用存储的 proc,其中不接受将空值传递给存储的 proc 调用,因此将值设置为空字符串。

You can use the logical or operator to crate this behavior in a single statement:您可以使用逻辑or运算符在单个语句中创建此行为:

SELECT *
FROM   persons p 
WHERE  (age < 0 OR p.age = age) AND 
       (class < 0 OR p.class = class) AND 
       (group < 0 OR p.group = group);

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

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