How do I check if an index exists on a table field in MySQL?

前端 未结 10 1268
孤独总比滥情好
孤独总比滥情好 2020-12-12 16:55

I\'ve needed to Google this a couple times, so I\'m sharing my Q/A.

相关标签:
10条回答
  • 2020-12-12 17:36

    Try:

    SELECT * FROM information_schema.statistics 
      WHERE table_schema = [DATABASE NAME] 
        AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]
    

    It will tell you if there is an index of any kind on a certain column without the need to know the name given to the index. It will also work in a stored procedure (as opposed to show index)

    0 讨论(0)
  • 2020-12-12 17:37

    Use SHOW INDEX like so:

    SHOW INDEX FROM [tablename]
    

    Docs: https://dev.mysql.com/doc/refman/5.0/en/show-index.html

    0 讨论(0)
  • 2020-12-12 17:40

    You can't run a specific show index query because it will throw an error if an index does not exist. Therefore, you have to grab all indexes into an array and loop through them if you want to avoid any SQL errors.

    Heres how I do it. I grab all of the indexes from the table (in this case, leads) and then, in a foreach loop, check if the column name (in this case, province) exists or not.

    $this->name = 'province';
    
    $stm = $this->db->prepare('show index from `leads`');
    $stm->execute();
    $res = $stm->fetchAll();
    $index_exists = false;
    
    foreach ($res as $r) {
        if ($r['Column_name'] == $this->name) {
            $index_exists = true;
        }
    }
    

    This way you can really narrow down the index attributes. Do a print_r of $res in order to see what you can work with.

    0 讨论(0)
  • 2020-12-12 17:42
    SHOW KEYS FROM  tablename WHERE Key_name='unique key name'
    

    you can find if there exists an unique key in the table

    0 讨论(0)
提交回复
热议问题