MySQL counts items in a database based on how many unique values ​​there are in a field

(Sorry for the title, I really don't know how the phrase is :-))

I have a table with date and uid fields.

I need to get the uid count for each date, currently I am doing this in php doing multiple queries like this:

SELECT COUNT(uid) FROM users where Date = 'xxx';

      

Is there an easy way to achieve this with just an SQL query?

+2


a source to share


3 answers


Use the group by clause:



SELECT Date, COUNT(uid) FROM users group by Date;

      

+4


a source


To count the number of unique values ​​use DISTINCT

:

SELECT COUNT(DISTINCT uid) AS cnt
FROM users
GROUP BY `Date`

      



If your column is datetime, you should use the DATE function to get only a portion of the date:

SELECT COUNT(DISTINCT uid) AS cnt
FROM users
GROUP BY DATE(`Date`)

      

+1


a source


SELECT Date, COUNT(uid) FROM users GROUP BY Date

      

0


a source







All Articles