MySql 存储过程组合

标签 mysql sql stored-procedures

Si 我有这个 MySql 存储过程,用于 gridview 过滤器。对于 3 列,我必须编写这么多查询组合。我必须在 7 列上使用过滤器,这将产生 7x7x7x7x7x7x7 数字组合。有没有更好的方法来实现这一点?

CREATE DEFINER=`root`@`localhost` PROCEDURE `GetApprovedData`
(in siteValue varchar(45),
 in skillValue varchar(100), in shiftValue varchar(100))
 BEGIN

 IF siteValue IS NULL and skillValue IS NULL and shiftValue IS NULL THEN 
  select * from approved;

 ELSEIF siteValue IS NULL and skillValue IS NULL and shiftValue IS NOT NULL    THEN
  select * from approved where shift = shiftValue;

 ELSEIF siteValue IS NULL and skillValue IS NOT NULL and shiftValue IS NULL THEN
  select * from approved where skill = skillValue;

 ELSEIF siteValue IS NOT NULL and skillValue IS NULL and shiftValue IS NULL THEN
  select * from approved where site = siteValue;

 ELSEIF siteValue IS NULL and skillValue IS NOT NULL and shiftValue IS NOT NULL THEN
  select * from approved where skill = skillValue and shift = shiftValue;

ELSEIF siteValue IS NOT NULL and skillValue IS NOT NULL and shiftValue IS NULL THEN
  select * from approved where site = siteValue and skill = skillValue;

ELSEIF siteValue IS NOT NULL and skillValue IS NULL and shiftValue IS NOT NULL THEN
  select * from approved where site = siteValue and shift = shiftValue;

ELSE        
  select * from approved where site = siteValue and skill = skillValue and shift = shiftValue;
END IF;

END

最佳答案

检查参数是否IS NULL或行的列值是否与参数的值匹配。

SELECT *
       FROM approved
       WHERE (sitevalue IS NULL
               OR site = sitevalue)
             AND (skillvalue IS NULL
                   OR skill = skillvalue)
             AND (shiftvalue IS NULL
                   OR shift = shiftvalue);

关于MySql 存储过程组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557636/

相关文章:

php - 尝试使用 CodeIgniter 存储过程 'call'

php - 调用时调用未定义的函数

mysql - ON 子句条件与 MySQL 中的 WHERE 子句条件 WITH JOIN

mysql - 将表限制为在其中一列中具有特定值的记录数量

sql - 如何编写 select inside case 语句

stored-procedures - EF5 需要更新 ContainerName.FunctionImportName 以在更新模型时访问存储过程,任何迷人的解决方案?

php - 在表单/电子邮件中复制/粘贴后出现奇怪的字符

php - 优化:memcached 与 mysql 内存

sql - oracle中的错误/异常处理

sql - 删除sql中所有重复的行