Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I prevent gaps while selecting by hour in MySQL?
    primarykey
    data
    text
    <p>I have the current SQL query to select requests per hour:</p> <pre><code>SELECT ((FLOOR( unix_timestamp(request_when)/(60*60))*(60*60))*1000) as request_when, COUNT(*) as amount FROM api_requests WHERE request_when BETWEEN SUBDATE(NOW(), INTERVAL 12 HOUR) AND NOW() GROUP BY HOUR(request_when) ORDER BY id DESC; </code></pre> <p><strong>The problem</strong> is that when there are 0 rows it just doesn't return a row, which is expected based on the query. However, I would like it to return 0 (with the correct datetime/timestamp). I have played around with other queries but none of them seem to work.</p> <p>An example output of what happens now is:</p> <pre><code>1289516400000 6 1289512800000 15 1289509200000 11 1289505600000 31 1289476800000 3 </code></pre> <p>You will notice it skipped a few hours. If you don't feel like doing the math, the datetime values of those timestamps are</p> <pre><code>2010-11-11 12:00:00 3 2010-11-11 20:00:00 31 2010-11-11 21:00:00 11 2010-11-11 22:00:00 15 2010-11-11 23:00:00 7 </code></pre> <p>I would like the times without rows (hours 13-19, for example) to return "0" instead of no row. This would make my wanted output to look like this:</p> <pre><code>2010-11-11 12:00:00 3 2010-11-11 13:00:00 0 2010-11-11 14:00:00 0 2010-11-11 15:00:00 0 2010-11-11 16:00:00 0 2010-11-11 17:00:00 0 2010-11-11 18:00:00 0 2010-11-11 19:00:00 0 2010-11-11 20:00:00 31 2010-11-11 21:00:00 11 2010-11-11 22:00:00 15 2010-11-11 23:00:00 7 </code></pre> <hr> <p>I went ahead and created a "helper" or "filler" table with the hours from 00 thru 23, and I tried using a RIGHT JOIN to it, but my query returns 0 rows and doesn't work at all. This query that doesn't work looks like this:</p> <pre><code>SELECT ((FLOOR( unix_timestamp(request_when)/(60*60))*(60*60))*1000) as request_when, IFNULL(COUNT(*),0) as amount FROM api_requests RIGHT JOIN _filler ON (HOUR(api_requests.`request_when`) = _filler.`hours`) WHERE request_when BETWEEN SUBDATE(NOW(), INTERVAL 12 HOUR) AND NOW() GROUP BY HOUR(request_when) ORDER BY api_requests.id DESC; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload