2013-02-14 25 views
0

我有三個表:如何從映射表組中獲取計數是PostgreSQL中的另一個表?

store 
===== 
    name 
    address 
    city 
    state 
    country 
    tag ..., 

post 
======= 
    title 
    summary 
    tags ... 

store_post_map 
================ 
(mapping on store and post based on tag). 

現在我想通過citystatecountrystore.id擺脫映射表組職位數,是什麼PostgreSQL中的SQL?

+0

請用實際列名說明您的模式並聲明您的外鍵。 – 2013-02-14 09:19:50

回答

0

基本上,它是這樣的:

SELECT store_id, count(*) AS posts_ct 
FROM store_post_map 
GROUP BY store_id; 

我們怎樣才能爲每個城市,州或國家,每個地區 可以有多個門店數?每個國家

計數:

SELECT s.country, count(*) AS posts_ct 
FROM store   s 
JOIN store_post_map sp ON sp.store_id = s.id 
GROUP BY 1; -- positional parameter - is the same as GROUP BY s.country here 

city計數可能需要GROUP BYareacountry此外,因爲一個城市的名字是不是唯一的。像:

SELECT s.city, s.area, s.country, count(*) AS posts_ct 
FROM store   s 
JOIN store_post_map sp ON sp.store_id = s.id 
GROUP BY 1, 2, 3; 
+0

謝謝Erwin, 我們通過這種方式獲得每家商店的計數,因爲我們在地圖表中有store_id,我們如何才能獲得每個城市,州或國家的計數,每個地區可以有多個商店? – bhupesh 2013-02-14 10:14:41

+0

@bhupesh:我添加了一個代碼示例和一些建議。 – 2013-02-14 10:25:03

+0

我們可以得到其他的列表格式存儲表,比如store.name有最大數量嗎? – bhupesh 2013-02-14 10:41:14

相關問題