zoukankan      html  css  js  c++  java
  • [MySql]索引的一些技巧

    一、多表子从查询

    多表查询时,子查询可能会出现触发不了索引的情况

    SELECT * FROM test_1 WHERE id in (SELECT id FROM test_publish WHERE id in (38,69));

    上面语句,test_1和test_public都WHERE了主键id,常理来说这个查询不存在问题,事实上主语句并不会触发索引,只有子语句触发了索引

    id select_type table type possible_keys key key_len ref rows extra
    1 SIMPLE test_1 ALL         5 Using where
    1 SIMPLE test_publish eq_ref PRIMARY PRIMARY 4 test.test_1.id 1 Using where

    这个时候可以把语句分拆成两个单独的语句去查询,或者关联表

    SELECT * FROM test_1 LEFT JOIN test_publish ON test_1.id = test_publish.id WHERE test_publish.id in (38,69);
    id select_type table type possible_keys key key_len ref rows extra
    1 SIMPLE test_1 range PRIMARY PRIMARY 4   2 Using where
    1 SIMPLE test_publish eq_ref PRIMARY PRIMARY 4 test.test_1.id 1 Using where

    二、手动强制索引和忽略索引

    1、mysql强制使用索引:force index(索引名或者主键PRI)

    例如:

    select * from table force index(PRI) limit 2;(强制使用主键)

    select * from table force index(ziduan1_index) limit 2;(强制使用索引"ziduan1_index")

    select * from table force index(PRI,ziduan1_index) limit 2;(强制使用索引"PRI和ziduan1_index")

    2、mysql禁止某个索引:ignore index(索引名或者主键PRI)

    例如:

    select * from table ignore index(PRI) limit 2;(禁止使用主键)

    select * from table ignore index(ziduan1_index) limit 2;(禁止使用索引"ziduan1_index")

    select * from table ignore index(PRI,ziduan1_index) limit 2;(禁止使用索引"PRI,ziduan1_index")

  • 相关阅读:
    科学计算和可视化,做数据分析与雷达图。
    Leetcode 429 N叉树的层序遍历
    Leetcode 867转置矩阵
    Leetcode 832 翻转图像
    Leetcode 1052 爱生气的书店老板
    Leetcode 337打家劫舍 III
    Leetcode 766 托普利茨矩阵
    Leetcode 1438绝对差不超过限制的最长连续子数组
    Leetcode 697 数组的度
    Leetcode 567 字符串的排列
  • 原文地址:https://www.cnblogs.com/yiyide266/p/7283635.html
Copyright © 2011-2022 走看看