2014-02-06 55 views
2

模式:GROUP BY和HAVING子句在同一查詢

place(pid, name, type, lat, lng, deleted)


I want to select count of places, grouping them by their type and having a distance of < 10 KM from a particular lat, lng

查詢:

SELECT count(p.type) as count 
FROM (place as p) 
where p.deleted != 1 
and p.pid in 
    (
    select p2.pid, 
      IFNULL(acos(sin((18.5236 *pi()/180)) * sin((p2.lat*pi()/180))+cos((18.5236 *pi()/180)) * cos((p2.lat *pi()/180)) * cos(((73.8478 - p2.lng)*pi()/180))) * 6371.009, 0) AS distance 
    from place p2 
    having `distance` < 10 
    ) 
group by p.type; 

錯誤:

Operand should contain 1 column(s)

那是因爲我選擇2列即在子select查詢PID距離。但是,如果不使用第二個選擇列,我如何計算距離。

+1

您IFNULL(ACOS ...)<10添加到WHERE條件在內部查詢和SELECT子句中刪除。 – wxyz

+0

@StuartLC MySql –

+0

你的子查詢應該只返回一列。 – Jade

回答

1

重寫你這樣的腳本

SELECT count(p.type) AS count, 
     -- remove this if not necessary 
     SUM(IFNULL(acos(sin((18.5236 *pi()/180)) * sin((p.lat*pi()/180))+cos((18.5236 *pi()/180)) * cos((p.lat *pi()/180)) * cos(((73.8478 - p.lng)*pi()/180))) * 6371.009, 0)) AS distance 

FROM place AS p 
WHERE p.deleted != 1 
GROUP BY p.type 
HAVING SUM(IFNULL(acos(sin((18.5236 *pi()/180)) * sin((p.lat*pi()/180))+cos((18.5236 *pi()/180)) * cos((p.lat *pi()/180)) * cos(((73.8478 - p.lng)*pi()/180))) * 6371.009, 0)) < 10