LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

大学生管理アプリの作成4(MySQLのテーブルを作成しよう)

Last updated at Posted at 2019-05-17

MySQLのテーブル定義を考えよう

この記事は少し難しいので、よくわからないという人は、流して読むだけで大丈夫です。

テーブルを作成する時の注意点

  • create tableの簡単な文法の説明
  • テーブル名は複数形にします
  • テーブルには、AUTO_INCREMENTと呼ばれるidを必ず付与します。
  • 「テーブルの単数形id」は、他のテーブルのidを意味します。例えば、studentidは生徒テーブルのidです。
  • テーブル作成における基本的な文法は、ここでは深く気にしないで下さい。MySQLの中でコピペすれば、テーブルを作成することができます。

テーブルを定義するSQL

生徒テーブル

  • 一意となるidをbigint型で定義
  • 学科テーブル(subject)と繋ぐidをint(数字)で定義
  • 名前をvarchar(文字列)で定義
  • emailをvarchar(文字列)で定義
  • 性別をint(数字)で定義
  • 年齢をint(数字)で定義
  • 意見をtext(長い文字列)で定義
students
CREATE TABLE `students` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `subject_id` bigint(20) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(11) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `opinion` text,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

学科テーブル

  • 一意となるidをbigint型で定義
  • 名前をvarchar(文字列)で定義
subjects
CREATE TABLE `subjects` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8

サークルテーブル

  • 一意となるidをbigint型で定義
  • 名前をvarchar(文字列)で定義
clubs
CREATE TABLE `clubs` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

生徒とサークルの関連性である「多対多」を表すテーブル

  • 一意となるidをbigint型で定義
  • student_idをbigint型で定義
  • club_idをbigint型で定義
club_students
CREATE TABLE `club_students` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `student_id` bigint(20) DEFAULT NULL,
  `club_id` bigint(20) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
  • 一意となるidをbigint型で定義
  • 生徒テーブル(students)と繋ぐidをint(数字)で定義
  • 名前をvarchar(文字列)で定義
  • 点数をint(数字)で定義
exam_results
CREATE TABLE `exam_results` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `student_id` bigint(20) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

関連性とIDの持たせ方を覚えておこう

下記の図に示したように、「一対多」の場合は、「多のテーブル」に「一のテーブルのid」を持たせます。
「多対多」の場合は、追加でテーブルを作成して、そのテーブルに「それぞれのid」を持たせます。

college_4.png

大学生管理アプリの作成5

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up