Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform COUNT() or COUNT(*)

Tags:

mysql

count

I have a list of tags in a database.

Ex:

villan
hero
spiderman
superman
superman

I wanted to obtain a sorted list of the tag names in ascending order and the number of times the unique tag appeared in the database. I wrote this code:

Ex:

 SELECT hashtag.tag_name
      , COUNT( * ) AS number
   FROM hashtag 
  GROUP BY hashtag.tag_name
  ORDER BY hashtag.tag_name ASC

This yields the correct result:

 hero      , 1
 spiderman , 1
 superman  , 2
 villan    , 1

How can I obtain the full COUNT of this entire list. The answer should be 4 in this case because there are naturally 4 rows. I can't seem to get a correct COUNT() without the statement failing.

Thanks so much for the help! :)

like image 530
ninu Avatar asked May 27 '10 04:05

ninu


2 Answers

SELECT COUNT(DISTINCT `tag_name`) FROM `hashtag`
like image 130
zerkms Avatar answered Sep 25 '22 18:09

zerkms


Use COUNT DISTINCT(hashtag.tag_name) -- it can't go in the same SELECT you have (except with a UNION of course), but on a SELECT of its own (or an appropriate UNION) it will give the result you want.

like image 43
Alex Martelli Avatar answered Sep 22 '22 18:09

Alex Martelli