简体   繁体   English

MySQL查询减去2计数结果少0

[英]Mysql query deducting 2 counts result less 0

I have aa query which retrieves 2 times a count from 2 tables. 我有一个查询,它从2个表中检索2次计数。 Now in the same query it has (countresult1-countresult2) AS restresult 现在在同一查询中它具有(countresult1-countresult2)AS restresult

Now restresult is sometimes less than 0 (eq -10) but I want it to return 0 if it's under 0. 现在restresult有时小于0(eq -10),但是如果它小于0,我希望它返回0。

Uhm did I explan that right? 嗯,我说对了吗? Minimum value should be 0 not below. 最小值应为0或更低。

Cheers!!! 干杯!!!

GREATEST((countresult1-countresult2), 0) AS restresult
if (countresult1<countresult2, 0, countresult1-countresult2) as restresult

countresult1和countresult2都不会返回负数,因此上面的代码应该是安全的

没有看到您的查询,您可能会遇到类似...

MAX( if( countresult1-countresult2 < 0, 0, countresult1-countresult2 )) as YourResult

Until Now I didn't know there was if-else commands in SQL, but I found some. 直到现在,我还不知道SQL中是否有if-else命令,但我发现了一些。

you will want to use: 您将要使用:

WHEN (countresult1-countresult2) < 0 THEN 0 ELSE (countresult1-countresult2)

Here is the source where I found the SQL information: http://www.tizag.com/sqlTutorial/sqlcase.php 这是我找到SQL信息的来源: http : //www.tizag.com/sqlTutorial/sqlcase.php

Take the maximum of 0 and the value you calculated, like this: 取最大值0和您计算出的值,如下所示:

SELECT GREATEST(your-restresult-query,0)
FROM ... (etc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM