【问题标题】:SELECT count from multiple tables between 2 dates with BIG DATA使用大数据从两个日期之间的多个表中选择计数
【发布时间】:2018-07-01 08:14:56
【问题描述】:

我有多个表(相同的列结构),我希望在 2 个日期范围之间计算行数。现在它给了我每个表的所有记录。每个表都有大约 70 万条记录,这使得搜索速度也很慢。 我没有得到正确的查询。 以下查询是我目前所拥有的。

$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 代码:

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();
}

【问题讨论】:

  • 如果您只需要计数,您可以使用SELECT count(datetime) FROM ...
  • datetime 列添加索引应该可以加快查询速度(我认为)。旁注:您可能想阅读有关在 PHP 中使用语句的信息,这可以让您在尝试编写查询时更轻松。
  • @FelippeDuarte:我试过 count() 但还是一样..
  • SELECT count(datetime) as whatever_alias - 尝试使用别名。另外,$Tuesday != $tuesday。如果那是你的真实代码,你应该得到一个错误,因为它是一个未定义的变量。
  • 您应该 a) 向我们展示您用于运行查询的实际 PHP 代码,并且 b) 最好向我们展示正在运行的原始 MySQL 查询。可能不是你想的那样。

标签: php mysql bigdata multiple-tables


【解决方案1】:

您可以使用子请求对每个表进行计数并对结果求和。

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;

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 2012-03-03
    • 1970-01-01
    • 2012-12-21
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多