创建索引

  1. 创建索引

    1. 索引是一种提高数据库查询性能的数据结构,可以快速定位表中的特定数据。创建索引是MySQL高效运行的重要部分,尤其是在处理大量数据时。 显示表 singer 中, 已经存在的索引:

      show index from singer \G
      mysql> show index from singer \G
      Empty set (0.018 sec)
      
      mysql>
                                                     
      把 ; 换成 \G 是纵向显示。 注意:尽管 mysql 不区分大小写, 但这里 \G 需要大写。 上面显示表 singer 没有索引。

    2. 在表 singer 的列 song 上创建名为 song_index 的索引

      create index song_index on singer (song);
      mysql>  create index  song_index on singer (song);
      Query OK, 0 rows affected (7.887 sec)
      Records: 0  Duplicates: 0  Warnings: 0
      
      mysql>
                                                     
      显示表 singer 中, 已经存在的索引:
      show index from singer \G
      mysql> show index from singer \G
      *************************** 1. row ***************************
              Table: singer
         Non_unique: 1
           Key_name: song_index
       Seq_in_index: 1
        Column_name: song
          Collation: A
        Cardinality: 0
           Sub_part: NULL
             Packed: NULL
               Null: YES
         Index_type: BTREE
            Comment:
      Index_comment:
            Visible: YES
         Expression: NULL
      1 row in set (0.018 sec)
      
      mysql>
                                              
      song_index 正是刚才创建的索引。

    3. 删除表 singer 中的索引 song_index

      drop index song_index on singer;
      mysql> drop index song_index on singer;
      Query OK, 0 rows affected (1.259 sec)
      Records: 0  Duplicates: 0  Warnings: 0
      
      mysql>