I have a mysql table like with the following rows:
id | event_type | occurance_date | ipaddress
I want to get the days, unique visits and total visits / day. This is pretty easy to do with 2 queries but I want to make only one.
So i thought
To get the days i can
SELECT DISTINCT(occurance_date) as day FROM statistics WHERE event_type = 'visit'
ORDER BY id DESC LIMIT 14;
To get unique visits / day
SELECT COUNT(DISTINCT(ipaddress)) as unique_visits FROM statistics WHERE occurance_date = '2011-05-11';
To get all visits / day
SELECT COUNT(id) as total_visits FROM statistics WHERE occurance_date = '2011-05-11';
The problem is how can I make a single query to return me the all the days, with unique_visits and total_visits.
(2011-05-11 should be replaced by date, it’s just an example)
Any suggestion is more then welcomed.
Thanks.
Annotated version:
First we do a SELECT count(all rows)
Plus a count of the distinct ipaddresses
From statistics, I’ve added an alias, but that’s just out of habit. It is not needed.
Remember you wanted only rows that had event_type ‘visit’.
You also had some information need about that, but you did not want to filter those out, you just wanted to see them as separate items in the result.
So the only filter we have is
event_type.We group the result by occurrence date, if you leave this line out, you will only see one line. Put it back in to see the difference.
And we order the results by number of visits, except I didn’t want to rewrite
count(distinct(s1.ipaddress))so I wrote the aliasunique_visits; this is allowed (and even encouraged in anorder byclause.)Links:
Group by, never mind about this myth part, just read the description of how group by works:
http://dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html
Count: http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html