2013-01-22 38 views
0

大於MIN,小於這是我的查詢:MySQL的:WHERE值大於最大

SELECT wp_posts.ID, wp_posts.post_title, lat.meta_value AS latitude, lng.meta_value AS longitude, info1.meta_value AS street_no, info2.meta_value AS street, info3.meta_value AS street_suffix, price.meta_value AS price, 
     (3959 * acos(cos(radians('{$latitude}')) * cos(radians(lat.meta_value)) * cos(radians(lng.meta_value) - radians('{$longitude}')) + sin(radians('{$latitude}')) * sin(radians(lat.meta_value)))) AS distance 

     FROM wp_posts 

     LEFT JOIN wp_postmeta AS lat 
      ON lat.post_id = wp_posts.ID 
       AND lat.meta_key = 'property_lat' 

     LEFT JOIN wp_postmeta AS lng 
      ON lng.post_id = wp_posts.ID 
       AND lng.meta_key = 'property_long' 

     LEFT JOIN wp_postmeta AS info1 
      ON info1.post_id = wp_posts.ID 
       AND info1.meta_key = 'street_no' 

     LEFT JOIN wp_postmeta AS info2 
      ON info2.post_id = wp_posts.ID 
       AND info2.meta_key = 'street' 

     LEFT JOIN wp_postmeta AS info3 
      ON info3.post_id = wp_posts.ID 
       AND info3.meta_key = 'street_suffix' 

     LEFT JOIN wp_postmeta AS price 
      ON price.post_id = wp_posts.ID 
       AND price.meta_key = 'price_current' 

     WHERE lat.meta_key IS NOT NULL 

     HAVING distance < 30 

     LIMIT 0, 20 

我需要更新WHERE statemtent考慮到price_minprice_max值...只有返回結果WHERE price is >= {$price_min} AND <= {$price_max}

我希望是有道理的......

+1

你試過嗎? 'WHERE lat.meta_key不爲NULL且價格> = {$ price_min} AND <= {$ price_max}'可惜,如果您沒有:)相應地添加正確的表別名。 – bonCodigo

+0

'你的SQL語法錯誤;' – dcolumbus

回答

0

假設你只是每個ID獲取一條記錄,我建議你重寫查詢爲聚合:

select p.*, 
     (3959 * acos(cos(radians('{$latitude}')) * cos(radians(latitude)) * cos(radians(longitude) - radians('{$longitude}')) + sin(radians('{$latitude}')) * sin(radians(latitude)))) AS distance 
from (select p.id, 
      max(case when meta_key = 'property_lat' then meta_value end) as latitude, 
      max(case when meta_key = 'property_long' then meta_value end) as longitude, 
      max(case when meta_key = 'street_no' then meta_value end) as street_no, 
      max(case when meta_key = 'street' then meta_value end) as street, 
      max(case when meta_key = 'street_suffix' then meta_value end) as street_suffix, 
      max(case when meta_key = 'price_current' then meta_value end) as price_current 
     from wp_posts p 
     group by p.id 
    ) p 
WHERE latitude IS NOT NULL and distance < 30 
LIMIT 0, 20 

此查詢未經測試,因此可能有語法錯誤。

通過這樣的結構,你可以添加:

price_current is >= {$price_min} AND <= {$price_max} 

到外部查詢。我假設你的意思是price_current,因爲價格不在原始查詢中。

+0

在這種情況下,外部查詢是什麼? – dcolumbus

+0

這是一種定義新列和在where子句中使用這些列的方法。這似乎是你在原始查詢中使用'having'子句的原因 - 我發現這很混亂,因爲'having'子句應該暗示'group by'。 –

+0

錯誤:通過p.id從wp_posts p組'接近')p WHERE緯度不爲NULL並且di'在第10行' – dcolumbus