MySQL - 6、索引的创建、删除

0、首先,创建数据库和表:

CREATE DATABASE IF NOT EXISTS my_database;

USE my_database;

CREATE TABLE IF NOT EXISTS students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  age INT NOT NULL,
  gender ENUM('Male', 'Female') NOT NULL,
  address VARCHAR(100),
  CONSTRAINT chk_age CHECK (age >= 18)
);

CREATE TABLE IF NOT EXISTS courses (
  id INT AUTO_INCREMENT PRIMARY KEY,
  course_name VARCHAR(50) NOT NULL,
  credits INT NOT NULL,
  department VARCHAR(50),
  CONSTRAINT uc_course_name UNIQUE (course_name)
);
create table if not exists departments
(
    dep_id   int         not null
        primary key,
    dep_name varchar(50) not null
);

1、插入一些测试数据:

INSERT INTO students (name, age, gender, address) VALUES
  ('lfsun-1', 20, 'Female', '123 Main St'),
  ('lfsun-2', 22, 'Male', '456 Elm St'),
  ('lfsun-3', 19, 'Male', '789 Oak St');

INSERT INTO courses (course_name, credits, department)
VALUES ('Math', 3, 1),
       ('History', 4, 2),
       ('Physics', 3, 4);

2、创建索引:

-- 创建 students 表的索引
CREATE INDEX idx_students_name ON students (name);

-- 创建 courses 表的主键索引
ALTER TABLE courses ADD PRIMARY KEY (id);

-- 创建 courses 表的外键索引
ALTER TABLE courses
    ADD FOREIGN KEY (department) REFERENCES departments (dep_id);

3、删除索引:

-- 删除 students 表的索引
DROP INDEX idx_students_name ON students;

-- 删除 courses 表的主键索引
ALTER TABLE courses DROP PRIMARY KEY;

-- 删除 courses 表的外键索引(courses_ibfk_1:外键的名字)
ALTER TABLE courses DROP FOREIGN KEY courses_ibfk_1;

猜你喜欢

转载自blog.csdn.net/qq_43116031/article/details/132000641