MySQL - 显示索引



MySQL 索引是一种特殊的查找表,用于简化数据库中的数据检索。它指向数据库中的实际数据。

MySQL 允许在表的一个或多个列上创建各种类型的索引。它们是

  • 主键索引

  • 唯一索引

  • 简单索引

  • 组合索引

  • 隐式索引

要检查表上是否定义了任何这些索引,MySQL 提供了 SHOW INDEX 语句。

MySQL SHOW INDEX 语句

MySQL 的 SHOW INDEX 语句用于列出有关表索引的信息。

MySQL 中的垂直格式输出(由 \G 指定)通常与该语句一起使用,以避免长行换行。

语法

以下是 SHOW INDEX 语句的基本语法:

SHOW INDEX FROM table_name;

示例

在此示例中,我们创建一个名为 CUSTOMERS 的新表,并使用以下 CREATE TABLE 查询将其主键索引添加到其中一列:

CREATE TABLE CUSTOMERS (
   ID INT NOT NULL,
   NAME VARCHAR (20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),       
   PRIMARY KEY(ID),
   INDEX(NAME)
);

现在,我们可以使用以下 SHOW INDEX 查询显示 CUSTOMERS 表上存在的索引:

SHOW INDEX FROM CUSTOMERS\G

输出

将显示垂直输出:

*************************** 1. row ************************
        Table: customers
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: ID
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
*************************** 2. row ************************
        Table: customers
   Non_unique: 1
     Key_name: NAME
 Seq_in_index: 1
  Column_name: NAME
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
2 rows in set (0.01 sec)

使用 IN 子句

在此示例中,让我们首先使用以下 CREATE INDEX 查询在 CUSTOMERS 表的 AGE 列上创建一个索引:

CREATE INDEX AGE_INDEX ON CUSTOMERS (AGE);

您还可以通过指定数据库名称来检索信息:

SHOW INDEX IN CUSTOMERS FROM sample\G

输出

输出将与上面相同:

*************************** 1. row ***************************
        Table: customers
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: ID
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
*************************** 2. row ***************************
        Table: customers
   Non_unique: 1
     Key_name: NAME
 Seq_in_index: 1
  Column_name: NAME
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
2 rows in set (0.01 sec)

使用 WHERE 子句

由于索引以表格格式显示,因此我们可以将 WHERE 子句与 SHOW INDEX 语句一起使用以检索与给定条件匹配的指定索引。

SHOW INDEX IN CUSTOMERS WHERE Column_name = 'NAME'\G

输出

显示在 NAME 列上创建的索引:

*************************** 1. row ************************
        Table: customers
   Non_unique: 1
     Key_name: NAME
 Seq_in_index: 1
  Column_name: NAME
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
1 row in set (0.00 sec)

使用客户端程序显示索引

我们还可以使用客户端程序显示 MySQL 表上的索引信息。

语法

以下是使用各种编程语言在 MySQL 表上显示索引的语法:

要通过 PHP 程序显示 MySQL 表中的索引,我们需要使用 mysqli 连接器提供的 query() 函数执行 SHOW INDEX 语句,如下所示:

$sql = "SHOW INDEX FROM tutorials_table";
$mysqli->query($sql);

要通过 JavaScript 程序显示 MySQL 表中的索引,我们需要使用 mysql2 库的 query() 函数执行 SHOW INDEX 语句,如下所示:

sql = "SHOW INDEXES FROM temp";
con.query(sql);  

要通过 Java 程序显示 MySQL 表中的索引,我们需要使用 JDBCexecuteQuery() 函数执行 SHOW INDEX 语句,如下所示:

String sql = "SHOW INDEXES FROM tutorials_tbl";
st.executeQuery(sql);

要通过 Python 程序显示 MySQL 表中的索引,我们需要使用 MySQL Connector/Pythonexecute() 函数执行 SHOW INDEX 语句,如下所示:

rename_view_query = "SHOW INDEXES FROM tutorials_tbl"
cursorObj.execute(rename_view_query)

示例

以下是程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if ($mysqli->connect_errno) {
    printf("Connect failed: %s
", $mysqli->connect_error); exit(); } // printf('Connected successfully.
'); // SHOW INDEX $sql = "SHOW INDEX FROM tutorials_table"; if ($index = $mysqli->query($sql)) { printf("Index shown successfully!.
"); while ($indx = mysqli_fetch_row($index)) { print_r($indx); } } if ($mysqli->errno) { printf("Index could not be shown!.
", $mysqli->error); } $mysqli->close();

输出

获得的输出如下:

Index shown successfully!.
Array
(
   [0] => tutorials_tbl
   [1] => 0
   [2] => PRIMARY
   [3] => 1
   [4] => tutorial_id
   [5] => A
   [6] => 3
   [7] =>
   [8] =>
   [9] =>
   [10] => BTREE
   [11] =>
   [12] =>
   [13] => YES
   [14] =>
)
Array
(
   [0] => tutorials_tbl
   [1] => 0
   [2] => UIID
   [3] => 1
   [4] => tutorial_id
   [5] => A
   [6] => 3
   [7] =>
   [8] =>
   [9] =>
   [10] => BTREE
   [11] =>
   [12] =>
   [13] => YES
   [14] =>
)
var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("--------------------------");

  sql = "create database TUTORIALS"
  con.query(sql);

  sql = "USE TUTORIALS"
  con.query(sql);

  sql = "CREATE TABLE temp (ID INT, Name VARCHAR(100), Age INT, City VARCHAR(100));"
  con.query(sql);

  sql = "INSERT INTO temp values(1, 'Radha', 29, 'Vishakhapatnam'), (2, 'Dev', 30, 'Hyderabad');"
  con.query(sql);

  //Creating Indexes
  sql = "CREATE INDEX sample_index ON temp (name) USING BTREE;"
  con.query(sql);

  sql = "CREATE INDEX composite_index on temp (ID, Name);"
  con.query(sql);

  //Displaying Indexes
  sql = "SHOW INDEXES FROM temp;"
  con.query(sql, function(err, result){
    if (err) throw err
    console.log(result);
  });

});      

输出

生成的输出如下:

Connected!
--------------------------
[
  {
    Table: 'temp',
    Non_unique: 1,
    Key_name: 'sample_index',
    Seq_in_index: 1,
    Column_name: 'Name',
    Collation: 'A',
    Cardinality: 2,
    Sub_part: null,
    Packed: null,
    Null: 'YES',
    Index_type: 'BTREE',
    Comment: '',
    Index_comment: '',
    Visible: 'YES',
    Expression: null
  },
  {
    Table: 'temp',
    Non_unique: 1,
    Key_name: 'composite_index',
    Seq_in_index: 1,
    Column_name: 'ID',
    Collation: 'A',
    Cardinality: 2,
    Sub_part: null,
    Packed: null,
    Null: 'YES',
    Index_type: 'BTREE',
    Comment: '',
    Index_comment: '',
    Visible: 'YES',
    Expression: null
  },
  {
    Table: 'temp',
    Non_unique: 1,
    Key_name: 'composite_index',
    Seq_in_index: 2,
    Column_name: 'Name',
    Collation: 'A',
    Cardinality: 2,
    Sub_part: null,
    Packed: null,
    Null: 'YES',
    Index_type: 'BTREE',
    Comment: '',
    Index_comment: '',
    Visible: 'YES',
    Expression: null
  }
] 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ShowIndex {
   public static void main(String[] args) {
      String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
      String username = "root";
      String password = "password";
      try {
         Class.forName("com.mysql.cj.jdbc.Driver");
         Connection connection = DriverManager.getConnection(url, username, password);
         Statement statement = connection.createStatement();
         System.out.println("Connected successfully...!");

         //Show index...!;
         String sql = "SHOW INDEXES FROM tutorials_tbl";
         ResultSet resultSet = statement.executeQuery(sql);
         System.out.println("Following are the indexes in tutorials_tbl");
         while (resultSet.next()){
            System.out.println(resultSet.getString(1)+ " "+ resultSet.getString(2)
                    +" "+resultSet.getString(3)+" " + resultSet.getString(4));
         }
         connection.close();
      } catch (Exception e) {
         System.out.println(e);
      }
   }
}    

输出

获得的输出如下所示:

Connected successfully...!
Following are the indexes in tutorials_tbl
tutorials_tbl 0 PRIMARY 1
tutorials_tbl 1 tid 1
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
table_name = 'tutorials_tbl'
cursorObj = connection.cursor()
show_indexes_query = f"SHOW INDEXES FROM {table_name}"
cursorObj.execute(show_indexes_query)
indexes = cursorObj.fetchall()
for index in indexes:
    print(f"Table: {index[2]}, Index Name: {index[3]}, Column Name: {index[4]}, Non-unique: {index[1]}")
cursorObj.close()
connection.close()                 

输出

以下是上述代码的输出:

Table: PRIMARY, Index Name: 1, Column Name: tutorial_id, Non-unique: 0
Table: idx_submission_date, Index Name: 1, Column Name: submission_date, Non-unique: 1  
mysql_statements_reference.htm
广告