MySql中有一个存储过程sp_select_from_persons
。此过程中有3个参数。 age, class, group
。这些参数值可以是-1或其他值。这些参数将在where
子句中使用
现在我想编写where子句,如果这些参数的任何值不是 -1 ,则将它们附加到where
子句中。例如:
如果age = -1,class = 7且group = 5,则select query将为:
SELECT * FROM persons p WHERE p.class = class AND p.group = group;
或者如果age = 25,class = -1并且group = -1则:
SELECT * FROM persons p WHERE p.age = 25;
等。
我不想使用如下所示的emnedded 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
有没有更好的方法来做到这一点。
答案 0 :(得分:2)
这是单行查询....试试这个
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
答案 1 :(得分:0)
您可以使用逻辑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);
答案 2 :(得分:0)
这样的事情对我也有用:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
.inner-div
{
text-align: center;
margin: 0 auto;
background-color: #fafafa;
border: 1px solid #ccc;
width: 40%;
min-height: 200px;
}
.button
{
background-color: #f2f2f2;
border: 1px solid #ccc;
padding: 10px 20px;
text-align: center;
font-size: 14px;
}
.button:hover
{
background-color: #f9f9f9;
border: 1px solid #aaa;
padding: 10px 20px;
text-align: center;
font-size: 14px;
cursor:pointer;
}
@media screen and (max-width: 1024px)
{
.inner-div
{
width: 60%;
}
}
@media screen and (max-width: 678px)
{
.inner-div
{
width: 90%;
}
.button
{
width: 100%;
}
}
</style>
</head>
<body>
<div class="inner-div">
<h1>
What are you looking for?</h1>
<br>
<button class="button">
Developer
</button>
<button class="button">
Entrepreneur
</button>
<button class="button">
Other
</button>
</div>
</body>
</html>
我的要求是从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
后端调用存储过程,其中不接受将空值传递给存储的proc调用,因此将值设置为空字符串。