需要获得最接近的最小值和最大值

时间:2015-09-01 13:03:50

标签: php mysql

这里我有一个关于获得最接近的最小值和最大值的查询。 我有一个范围:

Model.Student.Courses.Where(CourseName == 'C++');

现在我需要得到最接近的最小值和最大值。

我试过这个查询没有得到理想的结果。

2.43 - 3.57 lakhs

2 个答案:

答案 0 :(得分:0)

为什么你不使用'where'和'and'?

$othsimlar_prices = "select * 
                    from ncp_variant_cache
where minprice=ABS(exshowroom - ".$price_query['minprice'].")
and maxprice=ABS(exshowroom - ".$price_query['maxprice'].")
                    order by maxprice"

或者,如果您只有一列价格可以:

从your_table中选择*,其中介于interval1和interval2之间的价格

答案 1 :(得分:0)

获得它的粗略方式: -

SELECT exshowroom ,
        make,
        model,
        0 AS range_diff
FROM ncp_variant_cache 
WHERE exshowroom BETWEEN ".$price_query['minprice']." AND ".$price_query['maxprice']."
UNION
SELECT exshowroom ,
        make,
        model,
        ABS(exshowroom - ".$price_query['maxprice'].") AS range_diff
FROM ncp_variant_cache 
WHERE exshowroom > ".$price_query['maxprice']."
UNION
SELECT exshowroom ,
        make,
        model,
        ABS(".$price_query['minprice']." - exshowroom) AS range_diff
FROM ncp_variant_cache 
WHERE exshowroom < ".$price_query['minprice']."
ORDER BY range_diff
LIMIT 1

这使用3个联合查询。第一个获取价格范围内的任何记录,第二个获得最接近最大价格的记录,而第三个获得最接近最低价格的记录。结果按差异排序(差异设置为0范围内的差异)限制为1行。