查询联接表的计数

时间:2018-12-28 20:22:02

标签: sql postgresql

所以我有这个联接表

                                Table "public.pic_tags"
     Column |  Type  | Collation | Nullable |               Default
    --------+--------+-----------+----------+--------------------------------------
     id     | bigint |           | not null | nextval('pic_tags_id_seq'::regclass)
     tag_id | bigint |           |          |
     pic_id | uuid   |           |          |

我有这两个表

                                 Table "public.pics"
        Column        |            Type             | Collation | Nullable | Default
----------------------+-----------------------------+-----------+----------+---------
 id                   | uuid                        |           | not null |
 description          | text                        |           |          |
 asset                | character varying(255)      |           |          |

                          Table "public.tags"
 Column |  Type  | Collation | Nullable |             Default
--------+--------+-----------+----------+----------------------------------
 id     | bigint |           | not null | nextval('tags_id_seq'::regclass)
 name   | text   |           | not null |

所以我的问题是,如果我知道标签的名称是什么,如何查询给定名称为X的标签有多少张图片?

1 个答案:

答案 0 :(得分:1)

简单的JOINCOUNT将显示您想要的内容:

select count(*)
from tag t
join pic_tags pt on pt.tag_id = t.id
where t.name = 'X'