mysql 存储过程动态 Where 子句

mysql Stored Procedure Dynamic Where Clause

我在存储过程中有以下查询:

SELECT * 
FROM tempProfile
WHERE 1 = 1
and case    when l_primarymailingaddress = 'address1' then find_in_set(add1_stateid,p_stateid) or p_stateid is NULL
            when l_primarymailingaddress = 'address2' then find_in_set(add2_stateid,p_stateid) or p_stateid is NULL end;

我正在 p_stateid.

中传递 ID 列表

第一种情况找到匹配项,但第二种情况没有。

因此,例如,如果我传入 7,我会返回所有 add1_stateid 中有 7 的结果,查询不会返回 add2_stateid 中有 7 的结果。

与每个示例和描述进行比较,我发现这应该可行。

有人能看出我做错了什么吗?

非常感谢

好的 - 更新了我的回答以解决您具体解释了为什么使用 in_set 和 P_stateid 的问题。将 Case 语句分成两部分并使用 OR 比较它们是否有效?

SELECT * 
FROM tempProfile
WHERE 
case when l_primarymailingaddress = 'address1' AND find_in_set(add1_stateid,p_stateid) THEN 1 ELSE 0 END
OR
case when l_primarymailingaddress = 'address2' AND find_in_set(add2_stateid,p_stateid) THEN 1 ELSE 0 END
OR
p_stateid is NULL
;

第二次更新 - 在 p_stateid 为 NULL

时向 return 记录添加了另一个 OR