標籤:
寫在前面
項目中用到mysql資料庫,之前也沒用過mysql,今天就學下mysql的常用的文法,發現跟sql server的文法極其相似。用起來還是蠻簡單的。
一個例子
1、建立一個名為School的資料庫。
1、建立一個學生資訊表:學生id(自增,主鍵),姓名,年齡,性別,電話,籍貫,入學時間,所屬班級id(外鍵)。
2、建立一個學產生績表:成績id(自增,主鍵),科目,成績,學生id(外鍵),建立時間。
3、建立一個學生班級表:班級id(主鍵,自增),班級名稱。
建立表和資料庫
#如果存在資料庫School,則刪除。否則建立資料庫drop database if exists `School`;#建立資料庫create database `School`;use `School`;#如果存在資料表,則刪除,否則建立drop table if exists `tb_class`;#建立一個學生班級表:班級id(主鍵,自增),班級名稱。create table `tb_class`(`id` int(11) not null AUTO_INCREMENT primary key ,`Name` varchar(32) not null);Drop table if exists tb_student;#建立一個學生資訊表:學生id(自增,主鍵),姓名,年齡,性別,入學時間,所屬班級id(外鍵)。create table `tb_student`( `id` int(11) not null auto_increment primary key, `Name` varchar(32) not null, `Age` int default 0,check(`Age`>0 and `Age`<=100), `gender` boolean default 0,check(`gender`=0 or `gender`=1), `date` datetime default now());#建立一個學產生績表:成績id(自增,主鍵),科目,成績,學生id(外鍵),建立時間。drop table if exists `tb_score`;create table `tb_score`(`id` int(11) not null AUTO_INCREMENT PRIMARY key,`course` varchar(32) not null,`Score` float(3,1) not null,`stuId` int(11) not null , constraint `FK_Stuid` foreign key(`stuId`) references `tb_student`(`id`));
查詢建立的資料庫
show databases;
查看錶結構
use school;desc tb_student;
結果
修改學生資訊表的欄位date為createdate。
1 use school;2 alter table tb_student change `date` `createdate` datetime;
在學生資訊表姓名之後新增學生電話欄位。
use school;alter table tb_student add `phone` varchar(15) after `name`;
總結
建立資料庫和建立資料表的內容就學到這裡,如果用過sql server 這個學起來還是容易上手的。之後將學習資料表中的增刪改查。
mysql之建立資料庫,建立資料表