-3

I have multiple tables (same column structures) which I want to have the count rows between 2 date ranges. Right now it gives me all records from each table. Each table have around 700K records, which makes it also slow to search through. I'm not getting the right query for this. The below query is what I have so far.

$monday = '2018-01-15';
$tuesday = '2018-01-16';

SELECT count(datetime) FROM uptime_m1 WHERE datetime 
BETWEEN '$monday' and'$tuesday' and status = 'idle' 
UNION ALL 
SELECT (datetime) FROM uptime_m2 WHERE datetime 
BETWEEN '$monday' and'$tuesday' and status = 'idle';

PHP CODE:

if ($result = $mysqli->query("
SELECT count(datetime) FROM uptime_m1 WHERE datetime 
   BETWEEN '$monday' and'$tuesday' and status = 'idle' 
UNION ALL 
SELECT (datetime) FROM uptime_m2 WHERE datetime 
   BETWEEN '$monday' and'$tuesday' and status = 'idle';
")) {
   $row_cnt = $result->num_rows;
   $count_m1_idle_monday = $row_cnt;
   $result->close();
}
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
Marios
  • 41
  • 10

1 Answers1

0

You can use a subrequest to count each table and sum the result.

select
  (select count(*) from uptime_m1
   where datetime between '$monday' and '$tuesday' and status = 'idle')
+ (select count(*) from uptime_m2
   where datetime between '$monday' and '$tuesday' and status = 'idle')
as nbrows;
ebahi
  • 536
  • 2
  • 7