寫在前面
項目中用到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`;
為表tb_student添加字段classid,並設置為外鍵。
use school; alter table tb_student add classId int(11) not null; alter table tb_student add constraint `FK_class_student` foreign key(`classId`) references tb_class(`id`);
總結
創建數據庫和創建數據表的內容就學到這里,如果用過sql server 這個學起來還是容易上手的。之后將學習數據表中的增刪改查。