在mysql的存储过程中使用条件(关键字'IF'等)形成查询
Posted
技术标签:
【中文标题】在mysql的存储过程中使用条件(关键字\'IF\'等)形成查询【英文标题】:use conditions (keyword 'IF' etc) in the formation of queries in stored procedures in mysql在mysql的存储过程中使用条件(关键字'IF'等)形成查询 【发布时间】:2017-01-29 15:06:57 【问题描述】:我写了一个存储过程(mysql,我的第一步):
PROCEDURE `get_SiteAttendanceByPages`(IN _UserName VARCHAR(20) CHARSET utf8, IN _DateS BIGINT(20), IN _DateF BIGINT(20))
BEGIN
IF _UserName = '' THEN
SELECT
login_history.event_id,
COUNT(login_history.event_id) AS count
FROM
login_history
INNER JOIN
client_pages
ON
login_history.event_id = client_pages.id
WHERE
(login_history.time_stamp BETWEEN _DateS AND _DateF) AND client_pages.name LIKE '%[p]%'
GROUP BY
login_history.event_id
ORDER BY
client_pages.name;
ELSE
SELECT
login_history.event_id,
COUNT(login_history.event_id) AS count
FROM
login_history
INNER JOIN
client_pages
ON
login_history.event_id = client_pages.id
WHERE
login_history.user_name = _UserName AND (login_history.time_stamp BETWEEN _DateS AND _DateF) AND client_pages.name LIKE '%[p]%'
GROUP BY
login_history.event_id
ORDER BY
client_pages.name;
END IF;
END
事实上,我想编写更短的代码。为此,您只需更改从表中制作样本的条件。
是否可以实现mysql存储过程? 那些。做这样的事情:
WHERE
(_UserName == '') ? ('') : ('login_history.user_name = _UserName AND') (login_history.time_stamp BETWEEN _DateS AND _DateF) AND client_pages.name LIKE '%[p]%'
?
【问题讨论】:
在 mysql 中的 Store 过程或函数或触发器上尚不支持带有三元运算符的速记 if-else。 【参考方案1】:解决方案
SELECT
login_history.event_id,
COUNT(login_history.event_id) AS count
FROM
login_history
INNER JOIN
client_pages
ON
login_history.event_id = client_pages.id
WHERE
((_UserName <> '' AND login_history.user_name = _UserName) OR _UserName = '') AND (login_history.time_stamp BETWEEN _DateS AND _DateF) AND client_pages.name LIKE '%[p]%'
GROUP BY
login_history.event_id
ORDER BY
client_pages.name;
【讨论】:
以上是关于在mysql的存储过程中使用条件(关键字'IF'等)形成查询的主要内容,如果未能解决你的问题,请参考以下文章