我不太确定如何扩展这个查询以便我也可以有一个AVG(price_current)
列。。。而不必在查询返回后在PHP中计算这个值。
SELECT
listing_subtype, bedrooms, total_baths, tot_sqft_finished, price_current, latitude, longitude, (
3959 * acos (
cos ( radians(48.639) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-123.404) )
+ sin ( radians(48.639) )
* sin( radians( latitude ) )
)
) AS distance
FROM rets_property_resi
WHERE listing_subtype = 'Single Family Detached' AND
bedrooms >= 2 AND bedrooms <= 3 AND
total_baths >= 1 AND total_baths <= 2 AND
tot_sqft_finished >= 2000 AND tot_sqft_finished <= 2500
HAVING distance < 5
ORDER BY distance
LIMIT 0, 25;
最佳答案
我在这里做一些假设:
您可以在请求的房屋周围的给定半径内查找类似的房屋。在您要查询的表中,每个家庭都有一个主键。让我们在这里称之为primKey
。
另外,您需要的是所有返回家园的平均价格,其限制为0,25,而不是表中与WHERE
子句匹配的所有记录的平均价格。
因此,所有返回的行都将有一个带有平均值的额外字段,并且每行的字段都相同。
您将不得不再次运行与子查询相同的查询。但是,由于要限制AVG,因此必须在子查询中运行它来计算正确的AVG。
这真是笨重:
SELECT
rets_property_resi.listing_subtype, rets_property_resi.bedrooms, rets_property_resi.total_baths, rets_property_resi.tot_sqft_finished, rets_property_resi.price_current, rets_property_resi.latitude, rets_property_resi.longitude, (
3959 * acos (
cos ( radians(48.639) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-123.404) )
+ sin ( radians(48.639) )
* sin( radians( latitude ) )
)
) AS distance, outerSubQuery.averagePrice
FROM rets_property_resi
LEFT JOIN
(
SELECT innerSubQuery.primKey AS primKey, AVG(innerSubQuery.price_current) AS averagePrice
FROM
(SELECT
primKey, price_current, (
3959 * acos (
cos ( radians(48.639) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-123.404) )
+ sin ( radians(48.639) )
* sin( radians( latitude ) )
)
) AS distance
FROM rets_property_resi
WHERE listing_subtype = 'Single Family Detached' AND
bedrooms >= 2 AND bedrooms <= 3 AND
total_baths >= 1 AND total_baths <= 2 AND
tot_sqft_finished >= 2000 AND tot_sqft_finished <= 2500
HAVING distance < 5
ORDER BY distance
LIMIT 0, 25) AS innerSubQuery
GROUP BY innerSubQuery.primKey
) AS outerSubQuery ON (outerSubQuery.primKey = rets_property_resi.primKey)
WHERE listing_subtype = 'Single Family Detached' AND
bedrooms >= 2 AND bedrooms <= 3 AND
total_baths >= 1 AND total_baths <= 2 AND
tot_sqft_finished >= 2000 AND tot_sqft_finished <= 2500
HAVING distance < 5
ORDER BY distance
LIMIT 0, 25;
不过,我敢打赌有一个更优雅的版本。您最好在这里使用临时表,或者只在代码中计算。
关于mysql - SELECT列,但也添加AVG列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35851232/