简体   繁体   中英

MySQL query plan not using Index

I have a nested query and I trying to see if there is any full table scan in my query.

explain delete from ACCESS where ACCESS.MESSAGEID in (select ID from MESSAGE where MESSAGE.CID = 'xzy67sd’)\G

The sub query is hitting index but the first is not using index. Here is the query plan.

    *************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: ACCESS
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 18295
        Extra: Using where
*************************** 2. row ***************************
           id: 2
  select_type: DEPENDENT SUBQUERY
        table: MESSAGE
         type: unique_subquery
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 8
          ref: func
         rows: 1
        Extra: Using where

But if I separate the query and check the query plan then it is using index. I am not able to understand why and looking for some hints

explain delete from ACCESS where ACCESS.MESSAGEID in (2,3)\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: ACCESS
         type: range
possible_keys: ACCESS_ID1
key: ACCESS_ID1
      key_len: 8
          ref: const
         rows: 2
        Extra: Using where

Subquery select statement returns constant, so rather than using select statement I type integer and the query plan start picking index

select ID from MESSAGE where MESSAGE.CID = 'xzy67sd’)\G 

Thanks in advance

You don't need a subquery, here, and as a general rule, you shouldn't use one in MySQL unless you actually do need one.

DELETE a
  FROM ACCESS a
  JOIN MESSAGE m ON m.ID = a.MESSAGEID
 WHERE m.CID = 'xzy67sd’;

This will delete the rows from ACCESS while leaving MESSAGE alone because only ACCESS is listed (by its alias "a") between DELETE and FROM , which is where you specify which tables you want to delete matching rows from.

The optimizer should use the indexes appropriately.

https://dev.mysql.com/doc/refman/5.6/en/delete.html (multi-table syntax)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM