在SQL中添加Where子句花费的时间更少-为什么?

时间:2018-12-16 11:32:03

标签: sql where-clause query-analyzer

    @Override
    public void onBackPressed() 
    {
        if (exit)
        // Any practical instruction can be written : 
        //Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
        //startActivity(intent);

            YourActivity.this.finish();
        else 
        {
            Snackbar snkbr = Snackbar
                    .make(crdLayout, "Click once again to exit", Snackbar.LENGTH_LONG)
                    .setActionTextColor(Color.WHITE);
            View snackBarView = snkbr.getView();
            snackBarView.setBackgroundColor(ContextCompat.getColor(Context(), R.color.snackBarColor));
            snkbr.show();
            exit = true;
            new Handler().postDelayed(new Runnable() 
            {
                @Override
                public void run()
                {
                    exit = false;
                }
            }, 3 * 1000);
        }
    }

执行时间比:

select count(*) 
from table 

使用select count(*) from table where x = '1' here x is not an index 子句,SQL必须做一些额外的工作,以便为什么查询具有where子句的查询很快。

2 个答案:

答案 0 :(得分:2)

通常是因为您的索引包含列x

通常,count(*)需要扫描所有行或扫描最小的索引(取决于数据库)。

通过比较,与您的where子句相比,基本上有两种方法:

  • 扫描所有行并进行比较。
  • 在索引中查找符合条件的值。

第二种方法通常比第一种更快。

其他因素也可能起作用。例如,另一个过程可能是更新或插入行,这将锁锁定在表或表的部分上。这可能会减慢其他查询的速度。不过,原因很可能是存在索引。

答案 1 :(得分:1)

通过传递WHERE子句,您指示RDBMS仅需要扫描表的一部分才能找到结果。如果没有WHERE子句,则需要扫描所有表。这并不意味着一种解决方案将永远比另一种解决方案更快。

一种解决方案是否比另一种更快,实际上取决于多个因素,例如:

  • 表结构(例如,WHERE子句中的列上有索引),

  • 大小(行数)

  • 已过滤列中的数据分布

  • 统计数据的准确性(最近为该表计算了统计信息,其样本量为...)

基于这些因素,RDBMS的优化器将决定应使用哪种执行计划,最终将决定查询性能。