简体   繁体   中英

Mysql query deducting 2 counts result less 0

I have aa query which retrieves 2 times a count from 2 tables. Now in the same query it has (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.

Uhm did I explan that right? Minimum value should be 0 not below.

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.

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

Take the maximum of 0 and the value you calculated, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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