MySQL count elements in a database based on how many unique values there are in a field
(Sorry for the title, I don't really know how to phrase that :-) )
I have a table that has a date and a uid fields.
I need to g开发者_StackOverflow中文版et the number of uid for each date, currently I'm doing it in php running multiple queries like this one:
SELECT COUNT(uid) FROM users where Date = 'xxx';
Is there a simple way to achieve this with only an sql query?
Use the group by clause:
SELECT Date, COUNT(uid) FROM users group by Date;
To count the number of unique values use DISTINCT
:
SELECT COUNT(DISTINCT uid) AS cnt
FROM users
GROUP BY `Date`
If your column is a datetime then you should use the DATE function to get the date part only:
SELECT COUNT(DISTINCT uid) AS cnt
FROM users
GROUP BY DATE(`Date`)
SELECT Date, COUNT(uid) FROM users GROUP BY Date
精彩评论