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://: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
廣告