【问题标题】:Best way to count millions of rows between certain dates in MySQL在 MySQL 中计算特定日期之间数百万行的最佳方法
【发布时间】:2013-08-28 03:01:09
【问题描述】:

这是我创建表的 SQL:

$sql_create_table = "CREATE TABLE {$table_name} (
                  hit_id bigint(20) unsigned NOT NULL auto_increment,
                  user_id int(7) unsigned NOT NULL default '0',
                  optin_id int(8) unsigned NOT NULL default '0',
                  hit_date datetime NOT NULL default '0000-00-00 00:00:00',
                  hit_type varchar(10) NOT NULL default '',
                  PRIMARY KEY  (hit_id),
                  KEY user_id (user_id)
             ) $charset_collate; ";

我需要知道计算查询中行数的最快方法。我当前的查询并没有因为经过数百万行而减少它。

$sql = "SELECT hit_id FROM $table_name WHERE user_id = %d AND hit_type = %s AND hit_date >= FROM_UNIXTIME(%d) AND hit_date <= FROM_UNIXTIME(%d)";

我试过这个没有运气(没有返回正确的结果):

$sql = "SELECT COUNT(*) FROM $table_name WHERE user_id = %d AND hit_type = %s AND hit_date >= FROM_UNIXTIME(%d) AND hit_date <= FROM_UNIXTIME(%d)";

我需要做些什么来使这个查询高效,以便它不会对数百万行超时?我只是想统计指定参数集中的行数。

【问题讨论】:

  • 表是否有聚集索引?有索引吗?
  • 您需要在要搜索范围的列上放置索引。

标签: php mysql sql performance


【解决方案1】:

我不确定 FROM_UNIXTIME 函数的性能,但我要做的第一件事是在 hit_date 上创建一个索引。 http://dev.mysql.com/doc/refman/5.0/en/create-index.html

【讨论】:

  • 在 user_id 和 hit_type 上。 (经验法则:索引 WHERE 子句中使用的所有内容。)
  • 我不熟悉索引。你能举个例子吗?
猜你喜欢
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 2020-05-30
  • 2014-10-23
  • 1970-01-01
相关资源
最近更新 更多