更改选择列会使查询变慢

时间:2018-10-25 13:09:01

标签: mysql

两个查询:

SELECT
  e.*,
  rb.auto_id
FROM events e
LEFT JOIN rb ON e.some_key=rb.some_key
WHERE
  e.something='xyzzy' AND e.something_else IS NOT NULL
ORDER BY e.`timestamp` DESC
LIMIT 200

快速燃烧(0.01秒)

将rb.auto_id更改为rb.some_timestamp会使查询变慢

SELECT
  e.*,
  rb.some_timestamp
FROM events e
LEFT JOIN rb ON e.some_key=rb.some_key
WHERE
  e.something='xyzzy' AND e.something_else IS NOT NULL
ORDER BY e.`timestamp` DESC
LIMIT 200

看来我的查询应该已经具有来自RB的所有数据,所以为什么要花这么长时间?此外,rb表现在有零个记录。这会增长,但是为什么这里会有性能下降?

e.some_key和rb.some_key都被索引

在两个查询上运行EXPLAIN显示了两个不同的执行计划:

快速查询EXPLAIN

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: e
   partitions: NULL
         type: index
possible_keys: event_col1_index,event_col2_index,event_col3_index,event_col1_col_4_index,event_col1_col3_index
          key: **timestamp_index**
      key_len: 6
          ref: NULL
         rows: **580**
     filtered: 9.01
        Extra: Using where
*************************** 2. row ***************************
           id: 1
  select_type: SIMPLE
        table: s
   partitions: NULL
         type: eq_ref
possible_keys: id,id_index
          key: id
      key_len: 767
          ref: dbname.e.col_3
         rows: 1
     filtered: 100.00
        Extra: NULL
*************************** 3. row ***************************
           id: 1
  select_type: SIMPLE
        table: rb
   partitions: NULL
         type: ref
possible_keys: rb_col_1,rb_col_1_index
          key: rb_col_1
      key_len: 1023
          ref: func
         rows: 1
     filtered: 100.00
        Extra: Using where; Using index
3 rows in set, 1 warning (0.00 sec)

慢查询EXPLAIN

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: e
   partitions: NULL
         type: ref
possible_keys: event_col1_index,event_col2_index,event_col3_index,event_col1_col_4_index,event_col1_col3_index
          key: **event_col1_index**
      key_len: 767
          ref: const
         rows: **146832**
     filtered: 26.17
        Extra: Using where; Using temporary; Using filesort
*************************** 2. row ***************************
           id: 1
  select_type: SIMPLE
        table: s
   partitions: NULL
         type: eq_ref
possible_keys: id,id_index
          key: id
      key_len: 767
          ref: dbname.e.col_3
         rows: 1
     filtered: 100.00
        Extra: NULL
*************************** 3. row ***************************
           id: 1
  select_type: SIMPLE
        table: rb
   partitions: NULL
         type: ALL
possible_keys: rb_col_1,rb_col_1_index
          key: **NULL**
      key_len: NULL
          ref: NULL
         rows: 2
     filtered: 100.00
        Extra: Using where; Using join buffer (Block Nested Loop)
3 rows in set, 1 warning (0.00 sec

0 个答案:

没有答案