Search code examples
phpmysqltag-cloud

PHP & MySQL - How to count the number of times data was entered for a specific user?


Let's say I want to display the tags related to users_question_id 1 and I want to count the number of times that tag was entered for that question by 1 each time it was entered in-order to display the tags that where entered more bigger.

How would I do this using MySQL and PHP I have created two tables called questions_tags and tags.

Here is the MySQL tables layout

Table questions_tags

id  tag_id  users_questions_id
46  46      1
47  47      29
48  48      1
49  49      11
50  50      1
51  51      1
52  52      345
53  53      1
54  54      1
55  55      100
56  56      1
57  57      1
58  58      1
59  59      1
60  60      1

And here is the second table.

Table tags

id  tag
46  a
47  x
48  a
49  r
50  a
51  a
52  k
53  a
54  a
55  q
56  b
57  c
58  d
59  d
60  z

Solution

  •    SELECT t.tag,
              COUNT(q.tag_id) 'num'
         FROM QUESTIONS_TAGS q
         JOIN TAGS t ON t.id = q.tag_id
        WHERE q.users_questions_id = 1
     GROUP BY t.tag
     ORDER BY num DESC