Where条件导致查询不走索引的情况

本文通过四个具体场景探讨了SQL查询中索引无法被有效利用的情况,包括不等于操作、空值判断、函数调用及类型不匹配等,并提供了详细的执行计划对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建测试用表:test,test2,test3

SQL> create table test as select object_id, owner, object_name, created from dba_objects;

Table created
SQL >create table test2 as select * from test where owner in ('SYS','OAK');

Table created.

SQL >create index test_ind1 on test(object_id);

Index created.
SQL >create index  test2_ind1 on test2(owner);

SQL >exec dbms_stats.gather_table_stats(user,'test');

PL/SQL procedure successfully completed.


SQL >exec dbms_stats.gather_index_stats(user,'test_ind1');

PL/SQL procedure successfully completed.

SQL >exec dbms_stats.gather_table_stats(user,'test2');

PL/SQL procedure successfully completed.


SQL >exec dbms_stats.gather_index_stats(user,'test2_ind1');

PL/SQL procedure successfully completed.
SQL >exec dbms_stats.gather_table_stats(user,'test3');

PL/SQL procedure successfully completed.

SQL >exec dbms_stats.gather_index_stats(user,'test3_ind1');

PL/SQL procedure successfully completed.

SQL >select count(*) from test;

  COUNT(*)
----------
     61684

SQL >select count(*) from test where object_id is null;

  COUNT(*)
----------
        40

SQL >select count(*),owner from test2 group by owner;

  COUNT(*) OWNER
---------- ------------------------------
     23225 SYS
         2 OAK

SQL >create table test3(object_id varchar2(20), owner varchar2(30));

Table created.

SQL >insert into test3 select object_id,owner from test;

61684 rows created.

SQL >create index test3_ind1 on test3(object_id);

Index created.

情况一:
Where条件中存在不等于操作(<>,!=)
SQL >select * from table(dbms_xplan.display_cursor);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------------------
SQL_ID  9zfw20r27fb6j, child number 0
-------------------------------------
select /*+ gather_plan_statistics */ * from test2 where wner='OAK'

Plan hash value: 2486100180

------------------------------------------------------------------------------------------
| Id  | Operation                   | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |            |       |       |     2 (100)|          |
|   1 |  TABLE ACCESS BY INDEX ROWID| TEST2      |     1 |    40 |     2   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | TEST2_IND1 |     1 |       |     1   (0)| 00:00:01 |
------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("OWNER"='OAK')

SQL >select * from table(dbms_xplan.display_cursor);

PLAN_TABLE_OUTPUT
----------------------------------------------------------------------------
SQL_ID  1zpaqum6fznd8, child number 0
-------------------------------------
select /*+ gather_plan_statistics */ * from test2 where owner !='SYS'

Plan hash value: 300966803

---------------------------------------------------------------------------
| Id  | Operation         | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |       |       |       |    35 (100)|          |
|*  1 |  TABLE ACCESS FULL| TEST2 |     1 |    40 |    35   (3)| 00:00:01 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("OWNER"<>'SYS')


情况二:
Where条件中存在is null 或 is not null

SQL >select * from table(dbms_xplan.display_cursor);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------
SQL_ID  fyqmqv95dy7yx, child number 0
-------------------------------------
select /*+ gather_plan_statistics */ * from test where object_id is null

Plan hash value: 1357081020

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |       |       |    90 (100)|          |
|*  1 |  TABLE ACCESS FULL| TEST |    40 |  1640 |    90   (3)| 00:00:02 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("OBJECT_ID" IS NULL)


情况三:
使用函数,而没有基于函数的索引
SQL >select * from table(dbms_xplan.display_cursor);

PLAN_TABLE_OUTPUT
---------------------------------------------------------------------------
SQL_ID  2apc04k69zvww, child number 0
-------------------------------------
select /* gather_plan_statistics */ * from test2 where
lower(owner)='oak'

Plan hash value: 300966803

---------------------------------------------------------------------------
| Id  | Operation         | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |       |       |       |    35 (100)|          |
|*  1 |  TABLE ACCESS FULL| TEST2 |   232 |  9280 |    35   (3)| 00:00:01 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(LOWER("OWNER")='oak')


情况四:比较条件类型字段类型不匹配
SQL >select * from table(dbms_xplan.display_cursor);

PLAN_TABLE_OUTPUT
----------------------------------------------------------------------------
SQL_ID  fjj3yqs8dcq7z, child number 0
-------------------------------------
select /*+ gather_plan_statistics */ * from test3 where object_id=60

Plan hash value: 3306317399

---------------------------------------------------------------------------
| Id  | Operation         | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |       |       |       |    36 (100)|          |
|*  1 |  TABLE ACCESS FULL| TEST3 |     1 |    11 |    36   (9)| 00:00:01 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(TO_NUMBER("OBJECT_ID")=60)

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7419833/viewspace-675169/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/7419833/viewspace-675169/

<think>嗯,用户问的是MySQL关联查询索引的场景及原因,还有优化方法。首先,我得回忆一下索引的基本知识,以及关联查询索引如何起作用。根据引用里的内容,比如引用3提到组合索引使用第一列会失效,还有数据类型隐式转换会导致索引失效。还有引用2提到优化JOIN语句要确保连接字段索引,用EXPLAIN检查。 首先,用户可能想知道在哪些情况下JOIN操作会使用索引,比如连接字段索引,或者类型匹配,或者使用了函数导致索引失效。比如,如果连接的两个字段数据类型不同,比如一个INT一个VARCHAR,这时候可能索引。还有,如果在连接字段上用了函数,比如CONVERT或者SUBSTRING,也会导致索引失效。 然后,需要结合引用里的例子,比如test_user和test_order表,如果user_id在test_order里没有索引,那么JOIN的时候可能全表扫描。另外,当使用OR条件或者范围查询时,可能部分情况索引失效,比如引用3里的最佳左前缀法则,组合索引的问题。 优化方法的话,应该包括添加合适的索引,检查数据类型是否一致,避免在连接字段上使用函数或表达式,使用EXPLAIN分析执行计划。引用2提到可以创建索引、调整JOIN的顺序,或者使用临时表来处理子查询。 还要注意,当使用外连接时,比如LEFT JOIN,如果右表的连接字段没有索引,也会导致性能问题。可能用户需要了解这些细节,以及如何通过优化表结构或者查询语句来改善性能。 总结下来,需要列举常见的几种索引的场景,比如无索引、类型隐式转换、使用函数、OR条件、外键约束问题,然后针对每个场景给出优化方法。同时,结合引用中的例子和优化建议,确保回答准确且有依据。</think>### MySQL关联查询索引的场景及优化方法 #### 一、索引的典型场景及原因 1. **连接字段索引** - **场景**:当`JOIN`操作的连接字段(如`user_id`)在**被驱动表**(如`test_order`)中未建立索引时,查询会进行全表扫描。 - **示例**: ```sql SELECT * FROM test_user u JOIN test_order o ON u.id = o.user_id; -- 若test_order.user_id无索引,则全表扫描 ``` [^4] 2. **隐式类型转换** - **场景**:连接字段的数据类型一致(如`CHAR`与`INT`),导致索引失效。 - **示例**: ```sql SELECT * FROM test_user u JOIN test_order o ON u.id = CAST(o.user_id AS CHAR); -- 强制类型转换使索引失效 ``` [^3] 3. **函数或表达式操作** - **场景**:对连接字段使用函数(如`CONCAT()`、`SUBSTRING()`)或表达式时,索引无法生效。 - **示例**: ```sql SELECT * FROM test_user u JOIN test_order o ON SUBSTRING(u.user_name,1,3) = o.order_name; -- 函数操作破坏索引 ``` 4. **OR条件导致部分失效** - **场景**:`WHERE`子句中的`OR`条件若涉及非索引字段,可能导致索引部分失效。 - **示例**: ```sql SELECT * FROM test_user u JOIN test_order o ON u.id = o.user_id WHERE u.age > 18 OR o.pay = 0; -- 若o.pay无索引,部分条件无法使用索引 ``` 5. **外键约束缺失** - **场景**:外键关联的表未正确设置索引时,可能影响`JOIN`效率(即使MySQL强制要求外键索引,但实际查询仍需依赖索引)。 --- #### 二、优化方法 1. **添加必要索引** - **操作**:为被驱动表的连接字段创建索引。例如: ```sql ALTER TABLE test_order ADD INDEX idx_user_id(user_id); -- 优化JOIN性能 ``` [^2] 2. **确保数据类型一致** - **操作**:检查连接字段类型是否一致,例如将`VARCHAR`与`CHAR`统一为相同类型。 3. **避免字段操作** - **原则**:在连接字段上使用函数或表达式,可通过调整查询逻辑规避。 - **示例**: ```sql -- 原始低效写法 SELECT * FROM test_user u JOIN test_order o ON DATE(u.create_time) = o.order_date; -- 优化后(假设order_date为DATE类型) SELECT * FROM test_user u JOIN test_order o ON u.create_time BETWEEN o.order_date AND o.order_date + INTERVAL 1 DAY; ``` 4. **使用覆盖索引** - **操作**:若查询仅需索引字段,可创建覆盖索引减少回表操作。例如: ```sql ALTER TABLE test_order ADD INDEX idx_covering(user_id, order_name); ``` 5. **调整JOIN顺序** - **策略**:通过`STRAIGHT_JOIN`强制指定驱动表(小表驱动大表),或依赖优化器自动选择。 - **示例**: ```sql SELECT * FROM small_table s STRAIGHT_JOIN large_table l ON s.id = l.small_id; -- 明确指定驱动表 ``` [^2] 6. **减少JOIN层级** - **方法**:拆分复杂查询为多个简单步骤,使用临时表存储中间结果。 - **示例**: ```sql CREATE TEMPORARY TABLE tmp_users SELECT id FROM test_user WHERE age > 18; -- 提前过滤并存储中间结果 SELECT * FROM tmp_users u JOIN test_order o ON u.id = o.user_id; ``` --- #### 三、验证工具:EXPLAIN 使用`EXPLAIN`分析查询计划,重点关注以下字段: - **type**:若为`ALL`,说明全表扫描;若为`ref`或`eq_ref`,说明使用索引。 - **key**:显示实际使用的索引名称。 - **rows**:预估扫描行数,数值越大性能风险越高。 ```sql EXPLAIN SELECT * FROM test_user u JOIN test_order o ON u.id = o.user_id; ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值