Help write SQL query for counting

I have 2 tables as follows:

tags: id, version, name

tag_links: id, version, tag_id (foreign key to tags.id)

      

I need to write a SQL statement that returns how many times each tag_id occurs in the tag_links table.

For example:

tags:
    id  version  name
    --  -------  ------
     1        1  sport
     2        1  comedy

tag_links:
    id  version  tag_id
    --  -------  ------
     1        1       1
     2        1       1
     3        1       1
     4        1       2
     5        1       2

      

As a result, I need:

tag_id  times_occurred
------  --------------
     1               3
     2               2

      

I have little knowledge of SQL and I tried to write it, but :(

Thank.

+2


source to share


4 answers


You don't even need to join tables for this, since all the information you want is in the tag_links table.

select tag_id, count(*) as times_occurred
from tag_links
group by tag_id;

      



If you want tag names you will need to join tables, but it doesn't look like this.

+8


source


SELECT tag_id, COUNT(*) AS times_occurred
FROM tag_links
GROUP BY tag_id

      



+3


source


select id,count(*)  from tags inner join tag_links on tags.tag_id = tag_links.tag_id
group by id

      

0


source


SELECT   tag_id, 
         Count(*) As times_occurred
FROM     tag_links
GROUP BY tag_id

      

0


source







All Articles