简体   繁体   中英

How to fix this MySQL query

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM