tags:

views:

96

answers:

4

Hi all,

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 an SQL statement that returns how many times each tag_id occurs in 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

The result I need is:

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

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

Thank you.

+3  A: 
SELECT tag_id, COUNT(*) AS times_occurred
FROM tag_links
GROUP BY tag_id
cletus
+8  A: 

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

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

If you wanted the tag names, you'd need to join the tables but that doesn't appear to be the case here.

paxdiablo
If you count(tag_id), your query will run faster and require less overhead.
tsilb
I think that depends on the DBMS, @tslib. DB2/z execution plans show this as only requiring index access for tag_links.tag_id. Other lesser DBMS' may not be that clever :-) The SQL92 standard doesn't, to my knowledge, follow the "ignore nulls" rule for count(*), only for count(column), so a smart DBMS will only get the tag_id columns in the visible rows anyway.
paxdiablo
A: 
select id,count(*)  from tags inner join tag_links on tags.tag_id = tag_links.tag_id
group by id
Wael Dalloul
A: 
SELECT   tag_id, 
         Count(*) As times_occurred
FROM     tag_links
GROUP BY tag_id
Waheed
you are too late :(, the others are like code generation tools to write sql queries.:D
Wael Dalloul