数据表加快了内容显示速度



在数据表中,我使用两个查询,一个通过服务器端分页获取该特定日期范围内的记录,另一个用于获取该特定日期范围内的记录总数。我正在使用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 秒。如何克服这个问题。

如果您使用的是 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"将"忽略"通过的限制,为您提供可能元素的完整计数

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

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

溶液:

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

您需要在表daily_txns的中间和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';

最新更新