2013-12-23 52 views
0

我有一個類別表和一個項目表。按別名搜索而不顯示別名

每個項目都有經緯度讓我可以按距離搜索。

我想要做的是顯示每個類別以及在選擇的距離內該類別中有多少項目。

E.g.在我自己的經度和緯度1英里範圍內顯示電子類別中的所有電視。

這是我正在嘗試,但我不能有一個別名內的兩列,顯然,我想知道是否有更好的方法來做到這一點?

Here is a SQL fiddle

這裏的查詢:

SELECT *, (SELECT count(*),(3959 * acos(cos(radians(52.993252)) 
* cos(radians(latitude)) 
* cos(radians(longitude) - radians(-0.412470)) 
+ sin(radians(52.993252)) 
* sin(radians(latitude)))) AS distance 
FROM items 
WHERE category = category_id group by item_id 
HAVING distance < 1 ) AS howmanyCat, 
(SELECT name FROM categories WHERE category_id = c.parent) AS parname 
FROM categories c ORDER BY category_id, parent 

回答

1

首先,距離計算每個項目的開始,那麼在分類信息連接和聚合和過濾

select c.*, count(i.item_id) as numitems 
from category c left outer join 
    (SELECT i.*, (3959 * acos(cos(radians(52.993252)) * cos(radians(latitude)) 
        * cos(radians(longitude) - radians(-0.412470)) + sin(radians(52.993252)) 
        * sin(radians(latitude))) 
       ) AS distance 
     FROM items i 
    ) i 
    on c.category_id = i.category_id and distance < 1 
group by category_id; 
+0

非常感謝!!這可以修改爲顯示所有類別?即使它裏面有0件物品?原因是格式化,因爲父貓也在類別表 –

+0

是的,我將'where'條件移到'on'。 –

+0

太棒了!完美的作品...不能夠感謝你! –

1

這是你在尋找什麼:

SELECT categories.name, count(items.item_id) as cnt 
FROM items 
JOIN categories 
ON categories.category_id=items.category 
WHERE (3959 * acos(cos(radians(52.993252)) 
* cos(radians(latitude)) 
* cos(radians(longitude) - radians(-0.412470)) 
+ sin(radians(52.993252)) 
* sin(radians(latitude)))) < 1 
GROUP BY categories.category_id; 

這給出:

Tvs | 1

1

你可以把表達式計算嵌套SELECT內部的距離,然後再加入結果到categories表,就像這樣:

SELECT COUNT(*), cc.name FROM (
    SELECT 
     i.item_id 
    , c.category_id 
    , (3959 * acos(cos(radians(52.993252)) 
    * cos(radians(latitude)) 
    * cos(radians(longitude) - radians(-0.412470)) 
    + sin(radians(52.993252)) 
    * sin(radians(latitude)))) AS distance 
    FROM items i 
    JOIN categories c ON c.category_id = i.category 
) raw 
JOIN categories cc ON raw.category_id = cc.category_id AND raw.distance < 1 
GROUP BY cc.name 

嵌套查詢對了項目和類別,並增加了計算出的距離欄。然後,將外部查詢通過距離過濾器的行,並將它們分組,按類別產生所需的輸出:

COUNT(*) NAME 
-------- ---- 
1   TVs 

Demo on sqlfiddle.