-- 看到很多人,写SQL代码非常随意,想法固然没错:每种方法都可以,只是结果一样就行!
-- 但是,我想:养成良好的SQL风格,会使你终生受益!
-- 因为:有时不同的查询,得到同样的结果,其效率却相差甚远......
-- 请看:
-- 查询一表中昨天生成的数据
-- 原表mobilefrends中的cdate字段上有索引,创建索引语句是:create index mobilefrends_cdate_idx on mobilefrends(cdate);
---------------------------------------------------------------------------------------------------------------------
-- 方法一:用to_char()函数
hll@SZTYORA> select count(*) from mobilefrends where to_char(cdate,'yyyy-mm-dd')=to_char(sysdate-1,'yyyy-mm-dd');
COUNT(*)
----------
82119
已用时间: 00: 00: 17.18
执行计划
----------------------------------------------------------
Plan hash value: 3731074549
------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 8 | 11773 (16)| 00:02:22 |
| 1 | SORT AGGREGATE | | 1 | 8 | | |
|* 2 | INDEX FAST FULL SCAN| MOBILEFRENDS_CDATE_IDX | 129K| 1012K| 11773 (16)| 00:02:22 |
------------------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter(TO_CHAR(INTERNAL_FUNCTION("CDATE"),'yyyy-mm-dd')=TO_CHAR(SYSDATE@!-1,'yyyy
-mm-dd'))
统计信息
----------------------------------------------------------
1 recursive calls
0 db block gets
36896 consistent gets
0 physical reads
0 redo size
345 bytes sent via SQL*Net to client
338 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
---------------------------------------------------------------------------------------------------------------------
-- 方法二:用trunc()函数
hll@SZTYORA> select count(*) from mobilefrends where trunc(cdate)=trunc(sysdate-1);
COUNT(*)
----------
82119
已用时间: 00: 00: 16.32
执行计划
----------------------------------------------------------
Plan hash value: 3731074549
------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 8 | 12580 (22)| 00:02:31 |
| 1 | SORT AGGREGATE | | 1 | 8 | | |
详细解决方案
- 同志们:尽量让你的查询走索引吧! -解决思路
热度:85 发布时间:2016-04-24 08:10:37.0
相关解决方案