MySQL计算不在BETWEEN x和y之间的值之间的差异

时间:2018-02-15 04:58:32

标签: mysql

我有一个mysql查询(大致如下)查询表格以确定不属于建议指南的值;

SELECT 
    location.name, test.name, result.value
FROM
    results
        INNER JOIN
    location ON location.id = results.locationid
        INNER JOIN
    tests ON tests.id = results.testid
WHERE
    result.value NOT BETWEEN test.lowerlimit AND test.upperlimit
GROUP BY location.name

这将返回超出范围的测试,然后我计划计算推荐范围和我的结果之间的差异。我遇到的问题是,有时超出范围会低于范围,有时超出范围,所以我不能这样做(result.value - test.upperlimit)。

我是否可以在其中添加类似IF语句的内容,以便说明结果是< lowerlimit然后计算results.value - test.lowerlimit,还是> upperlimit然后计算results.value - test.upperlimit

1 个答案:

答案 0 :(得分:0)

查看MySQL control flow functions

以下是使用IF函数的示例:

SELECT 
    location.name, 
    test.name, 
    IF (result.value < test.lowerlimit, results.value - test.lowerlimit, results.value - test.upperlimit)
FROM
    results
        INNER JOIN
    location ON location.id = results.locationid
        INNER JOIN
    tests ON tests.id = results.testid
WHERE
    result.value NOT BETWEEN test.lowerlimit AND test.upperlimit
GROUP BY location.name

您也可以使用CASE语句,如SELECT中的以下内容:

CASE 
WHEN result.value < test.lowerlimit THEN 
    results.value - test.lowerlimit 
ELSE 
    results.value - test.upperlimit 
END