mysql if语句只能在存储过程中使用,MySQL问题:是否可以在存储过程中的SELECT语句中设置IF语句...

在MySQL Workbench中,遇到无法在WHERE子句中使用MAX(C.LastContact)聚合的问题。提出了通过在SELECT语句中设置IF语句作为替代方案,根据传递到存储过程的参数值来实现相同功能。示例代码展示了如何使用CASE WHEN语句来达成目的,同时调整了WHERE子句和GROUP BY子句。这种方法允许在不同参数条件下动态改变查询条件。

I am using MySql with Workbench

I have not been able to use the MAX(C.LastContact) agregate in the WHERE clause which is needed to get the correct results. I am thinking another way to do this might be to set up IF statements in the SELECT statement based on the value of a parameter passed into the Stored Procedure. Is this possible. I have not been able to get it to work. I am using Dynamic SQL. Below is a portion of the code:

SET SelectStmt =

"SELECT COUNT(distinct(C.LocationID))AS ''Total Locations'',

IF Parameter1 = ''all''

THEN do this

IF((select max(TIMESTAMPDIFF(minute, C1.LastContact, NOW() ))

from computers c1 where c1.locationid = c.locationid) >= @TimeToFail,''Fail'',''OK'')

AS ''Status'',

IF Parameter1 = ''fail''

THEN do this

IF Parameter1 = ''ok''

THEN do this

FROM

Computers AS C ";

SET WhereClause = CONCAT(WhereClause, " IFNULL(TIMESTAMPDIFF(minute, C.LastContact, NOW()),0) ",

''>='',@TimeToFail);

SET GroupBy = " GROUP BY C.LocationID ";

解决方案you can use CASE WHEN THEN statement to achieve this functionality. an example for this is as follows.

SET SelectStmt =

"SELECT COUNT(distinct(C.LocationID))AS 'Total Locations',

CASE

WHEN Parameter1 = 'all'

THEN --do this

--IF((select max(TIMESTAMPDIFF(minute, C1.LastContact, NOW() ))

--from computers c1 where c1.locationid = c.locationid) >= @TimeToFail,'Fail','OK')

--AS 'Status',

WHEN Parameter1 = 'fail'

THEN --do this

WHEN Parameter1 = 'ok'

THEN --do this

END AS 'Status'

FROM

Computers AS C ";

SET WhereClause = CONCAT(WhereClause, "IFNULL(TIMESTAMPDIFF(minute, C.LastContact, NOW()),0) ",

'>=',@TimeToFail);

SET GroupBy = "GROUP BY C.LocationID ";

please check and reply if it works.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值