你可以做到的是这样的
>设置两个等于要执行的查询的变量.
>当第一个不为空时,将另一个变量设置为等于正确的查询.
>使用存储过程执行该查询.
存储过程:
DELIMITER $$
CREATE PROCEDURE `dynamic_query`(in input varchar(255))
BEGIN
SET @a := input;
PREPARE stmt FROM @a;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;
您要执行的两个选择:
SET @A := "SELECT * FROM cfg_users JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId='0' AND sDisabled IS NULL AND iStatusId > 0 AND sDate = '2014-08-01' GROUP BY cfg_users.iUserId ORDER BY iStatusId, sName";
SET @B := "your other select here";
获得正确查询的定义:
SET @C := (
SELECT
CASE
WHEN EXISTS
( SELECT *
FROM cfg_users
JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid
WHERE iTeamId='0'
AND sDisabled IS NULL
AND iStatusId > 0
AND sDate = '2014-08-01'
GROUP BY cfg_users.iUserId
ORDER BY iStatusId, sName
)
THEN @A
ELSE @B
END
);
执行声明:
CALL dynamic_query(@C);