【问题标题】:Datatables speed up content display数据表加速内容显示
【发布时间】:2017-08-01 14:20:29
【问题描述】:

在数据表中,我使用两个查询,一个通过服务器端分页获取特定日期范围内的记录,另一个获取该特定日期范围内的记录总数。我正在使用 Postgresql 数据库

select * from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690' order by created_date desc limit 10;

select count(mid) from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690';

这是正确的做法还是有任何最好的方法。 如果第一个查询需要 20 秒,那么第二个查询需要 40 秒,显示结果的总时间超过 60 秒。如何克服这个问题。

【问题讨论】:

  • 第二个查询可以使用count(1)
  • 在不将任何内容加载到 Datatables 的情况下运行数据库中的每个查询需要多长时间?
  • 在第一次查询中,您可以获得前 10 条记录,然后您可以给order by 条件
  • 我的意思是你可以使用内部查询
  • 对于第二个查询,根据 SQL 标准,您无法使用 countorder by 条件减少执行时间,因为它会检查表中的所有行

标签: php database laravel datatables


【解决方案1】:

如果您使用的是 postgres,您可以使用它来将所有内容简化为一个查询

select *, count(*) OVER() AS full_count from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690' order by created_date desc limit 10;

“count(*) OVER() AS full_count”将“忽略”通过的限制,为您提供可能元素的完整计数

【讨论】:

  • 你能解释一下如何减少执行时间吗?
  • 这需要我更多的时间然后分别执行
  • daily_txns 表上总共有多少条记录?表上有索引吗?你用的是什么数据库?
  • 是的,我有 created_date 和 mid 的索引。我正在使用 postgress 数据库。其中有 2,50,00,000 条记录。
【解决方案2】:

解决方案取决于您的表索引,并且仅当索引正确且您的解决方案(如 count(*) 对您没有帮助时)才提供此答案。

但有时您可以尝试使用标志 SQL_CALC_FOUND_ROWS 进行查询,但我建议您在使用前阅读this问答。

解决方案:

select SQL_CALC_FOUND_ROWS * from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690' order by created_date desc limit 10;

并查询获取查询的总记录

SELECT FOUND_ROWS() as cnt

【讨论】:

    【解决方案3】:

    您需要为daily_txns 表的mid 和created_date 列添加索引。我也猜测 mid 会比 created_date 更严格,所以我建议先在查询中使用它,以便搜索减少更快。

    select * from daily_txns where mid='0446721M0008690' created_date <='2017-08-01' and created_date>='2017-07-01' order by created_date desc limit 10;
    
    select count(mid) from daily_txns where mid='0446721M0008690' and created_date <='2017-08-01' and created_date>='2017-07-01';
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      相关资源
      最近更新 更多