0

我有三张桌子:

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

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

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

现在我想从映射表组中获取帖子计数city,或者state,PostgreSQL中的SQL是什么?countrystore.id

4

1 回答 1

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 BY areacountry此外,因为城市名称几乎不是唯一的。像:

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;
于 2013-02-14T09:21:28.397 回答