[英]using conditional where clauses in mysql select statement
MySql 中有一個存儲過程sp_select_from_persons
。 這個過程中有3個參數。 age, class, group
。 這些參數值可以是 -1 或其他值。 這些參數將在where
子句中使用。
現在我想像這樣編寫 where 子句,如果這些參數的任何值不是-1,則將它們附加到where
子句中。 例如:
如果年齡 = -1,班級 = 7 且組 = 5,則選擇查詢將是:
SELECT * FROM persons p WHERE p.class = class AND p.group = group;
或者,如果年齡 = 25,班級 = -1 且組 = -1,則:
SELECT * FROM persons p WHERE p.age = 25;
等等。
我不想使用像下面這樣的嵌入式 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
有一個更好的方法嗎?
這是一個單行查詢....試試這個
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
像這樣的事情也對我有用:
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
我的要求是從基於Java/SpringFramework-based
后端調用存儲的 proc,其中不接受將空值傳遞給存儲的 proc 調用,因此將值設置為空字符串。
您可以使用邏輯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.