2

I have the following table called user_pin_tags with the following data that I need to query and show distinct tags and a count of each:

| user_id | pin_id | tag_id |
+---------+--------+--------+
    1     |   34   |   7
    2     |   34   |   7
    3     |   34   |   15   
    4     |   34   |   16   
    5     |   34   |   16   
    6     |   34   |   16   

Right now I am using the following query to get the distinct tag_ids

SELECT DISTINCT tag_id
FROM user_pin_tags
WHERE pin_id =  34

which gives the result of:

| tag_id |
+--------+
    7
    15
    16

I need to modify this query to give the distinct tag_ids as well as the count within that pin_id, so I want to generate this result set:

| tag_id | count |
+--------+-------+
    7    |   2
    15   |   1
    16   |   3

How can I modify this query to achieve this?

3 Answers 3

3

Use COUNT(*) and GROUP BY:

SELECT tag_id, COUNT(*) AS total
FROM user_pin_tags
WHERE pin_id =  34
GROUP BY tag_id
Sign up to request clarification or add additional context in comments.

Comments

2
SELECT 
   DISTINCT(tag_id)
   ,count(pin_id)
FROM user_pin_tags
WHERE pin_id =  34
GROUP BY tag_id

Group By should do it ... i think.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

Comments

1

You can group by the tag_id:

SELECT tag_id, COUNT(pin_id)
FROM user_pin_tags
WHERE pin_id =  34
GROUP BY tag_id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.