重要なポイント
解説
今までの学生マスタ(students_mst)への登録場合、連番の最大値を調べて登録する必要がありました。その手間を省くことができる機能として、自動採番=「auto_increment」があります。
構文
auto_increment
下記のテーブルレイアウトの通り、学生ID(student_id)の備考に、「auto_increment」と記述します。
※この表記は、企業によって表記がことなります。
create table [テーブル名](
[カラム名1] [型] [null/not null] auto_increment,
[カラム名2] [型] [null/not null],
[カラム名3] [型] [null/not null],
primary key (
[カラム名1]
)
);
<例題>
- テーブルレイアウトを基にテーブルを作成すること。(テーブル名は、「students_mst_ai」とする。)
create table students_mst_ai (
student_id int not null auto_increment,
student_name varchar(255) not null,
student_name_kana varchar(255) null,
student_number varchar(20) null,
department_id int null,
gender char(1) not null,
age int null,
test_score int null,
insert_at datetime not null,
update_at datetime not null,
delete_at datetime null,
primary key(
student_id
)
);
上記のテーブル構造になることで、insert文の学生ID(student_id)の記述が不要となります。そのカラムは自動で採番されるようになります。
insert into students_mst_ai(
student_name
,student_name_kana
,student_number
,department_id
,gender
,age
,test_score
,insert_at
,update_at
) values (
'井田 テスト'
,'イダ テスト'
,'21000000'
,1
,'0'
,20
,100
,now()
,now()
);