How to use MySQL index columns?

后端 未结 5 561
广开言路
广开言路 2020-12-29 09:39

When do you use each MySQL index type?

  • PRIMARY - Primary key columns?
  • UNIQUE - Foreign keys?
  • INDEX - ??

For really large table

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 10:28

    I'm not that familiar with MySQL, however I believe the following to be true across most database servers. An index is a balanced tree which is used to allow the database to scan the table for given data. For example say you have the following table.

    CREATE TABLE person (
        id    SERIAL,
        name  VARCHAR(20),
        dob   VARCHAR(20)
    );
    

    If you created an index on the 'name' field this would create in a balanced tree for that data in the table for the name column. Balanced tree data structures allow for faster searching of results (see http://www.solutionhacker.com/tag/balanced-tree/).

    You should note however indexing a column only allows you to search on the data as it is stored in the database. For example:

    This would not be able to search on the index and would instead do a sequential scan on the table, calling UPPER() on each of the column:name rows in the table.

    select *
    from person
    where UPPER(name) = "BOB";
    

    This would also have the following effect, because the index will be sorted starting with the first letter. Replacing the search term with "%B" would however use the index.

    select *
    from person
    where name like "%B"
    

提交回复
热议问题