1

Currently I have a system where a PHP script logs some information (time and "sid") of a visit when the page is loaded.

I then use:

SELECT *
FROM (
    SELECT COUNT(*), time
    FROM visit
    WHERE sid = $sid
    GROUP BY time
    ORDER BY time DESC
    LIMIT 14
) AS abc
ORDER BY time ASC

to get the results from the last fortnight in reverse order.

The problem with this query is that on days with no visits I do not get the result: 0, [time], but instead nothing. What would I do to get a result of zero on those days? Is it even possible in MySQL or would I have to process it with PHP?

Any help greatly appreciated!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
JJJollyjim
  • 5,837
  • 19
  • 56
  • 78

2 Answers2

2

You have to use a second table containing all dates (or use a subquery like below). So extend the subquery for table t till CURDATE()-13 for having last 14 days.

SELECT COUNT(*),t.time FROM (
  SELECT CURDATE() AS time
  UNION
  SELECT CURDATE()-1 AS time
  UNION
  SELECT CURDATE()-2 AS time
  UNION
  SELECT CURDATE()-3 AS time
  UNION
  SELECT CURDATE()-4 AS time
  UNION
  [...]
) AS t
LEFT JOIN visit AS v ON t.time=v.time AND v.sid=$sid
ORDER BY t.time DESC
rabudde
  • 7,498
  • 6
  • 53
  • 91
1

First of all if I remember correctly ORDER in a subquery is useless.

If I was using PostgreSQL I'd use generate_series() and outer join to get 0s for missing dates. Unfortunately MySQL has no such concept. I'd suggest to use temporary table filled with dates

Community
  • 1
  • 1
mlt
  • 1,595
  • 2
  • 21
  • 52