MySQL サンプルデータベース生成スクリプト

本サイトで MySQL を学ぶ際に使う、サンプルデータベース school_db の生成スクリプトです。

以下のスクリプトを実行して school_db データベースを生成してください。

school_db という名前のデータベースが既に存在する場合は削除されてしまいますので、ご注意ください。


MySQL サンプルデータベース生成スクリプト

DROP DATABASE IF EXISTS school_db;
CREATE DATABASE IF NOT EXISTS school_db;
USE school_db;

DROP TABLE IF EXISTS exam_results,
                     exams,
                     students;
                     
-----------------------------------------------

CREATE TABLE students (
    student_id      INT             NOT NULL AUTO_INCREMENT,
    student_number  VARCHAR(10)     NOT NULL,
    first_name      VARCHAR(50)     NOT NULL,
    last_name       VARCHAR(50)     NOT NULL,
    middle_name     VARCHAR(50)     NULL,
	birthday  	    DATE            NOT NULL,
    gender          ENUM ('M','F')  NOT NULL,
    paid_flag       BOOL            NOT NULL DEFAULT FALSE,
    PRIMARY KEY (student_id),
    UNIQUE KEY (student_number),
    CHECK (birthday >= '2000-01-01')
);

INSERT INTO students 
		(student_number, first_name, last_name, birthday, gender)
	VALUES 
		('S000001', 'Yuta', 'Tanaka', '2025-01-15', 'M'),
		('S000002', 'Sakura', 'Hata', '2025-07-07', 'F'),
        ('S000003', 'Aya', 'Tanaka', '2025-12-11', 'F'),
        ('S000004', 'Hiroki', 'Suzuki', '2026-02-23', 'M'),
		('S000005', 'Yuri', 'Sasaki', '2025-11-01', 'F'),
        ('S000006', 'Ryo', 'Saito', '2027-08-21', 'M');
        
-----------------------------------------------

CREATE TABLE exams (
    exam_id     	INT 		NOT NULL AUTO_INCREMENT,
    exam_name_en  	VARCHAR(50) NOT NULL,
    exam_name_jp  	VARCHAR(50) NOT NULL,
	PRIMARY KEY (exam_id)
);

INSERT INTO exams
    ( exam_name_en, exam_name_jp )
VALUES  
    ('Math 1', '数学1'),
    ('English 1', '英語1'),
    ('History 1', '歴史1');

-----------------------------------------------

CREATE TABLE exam_results (
    exam_result_id 	INT NOT NULL AUTO_INCREMENT,
    exam_id 		INT NULL,
    student_id		INT NULL, 
    score INT NULL,
    PRIMARY KEY (exam_result_id),
    FOREIGN KEY (exam_id) REFERENCES exams (exam_id),
	FOREIGN KEY (student_id) REFERENCES students (student_id)
);

INSERT INTO exam_results
    ( exam_id, student_id, score )
VALUES
    ( 1, 1, 85),
    ( 1, 2, 60),
    ( 1, 4, 98),
    ( 1, 5, 73),
    ( 2, 1, 77),
    ( 2, NULL, NULL),
    ( 2, 3, 92),
    ( 2, 4, 81);
© 2024 MySQL 入門