SELECT列还要添加AVG列

时间:2016-03-07 18:31:36

标签: mysql sql select average resultset

我不太确定如何扩展此查询以便我也可以拥有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; 

1 个答案:

答案 0 :(得分:0)

我将在这里做一些假设:

  1. 您在要求的半径范围内寻找类似的房屋/住宅。每个家庭都有一个您要查询的表中的主键。我们在这里打电话给primKey

  2. 此外,您希望所有归还房屋的平均价格限制为0.25,而不是表格中与您WHERE条款匹配的所有记录的AVG。

    < / LI>

    因此,所有返回的行都将包含一个额外字段,其中包含平均价格,并且每行都相同。

    您必须再次作为子查询运行相同的查询。但是,由于您要限制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; 
    

    我打赌有一个更优雅的版本。你最好在这里使用临时表,或者只是在代码中计算。