1. 程式人生 > >MySQL表:增、刪、改、表的基本介紹

MySQL表:增、刪、改、表的基本介紹

一、表的基本介紹

      1、資料型別

型別

描述

Char(長度)

定長字串,儲存空間大小固定,適合作為主鍵或外來鍵

Varchar(長度)

變長字串,儲存空間等於實際資料空間

double(有效數字位數,小數位)

數值型

Float(有效數字位數,小數位)

數值型

Int( 長度)

整型

bigint(長度)

長整型

Date

日期型

BLOB

Binary Large OBject(二進位制大物件)

CLOB

Character Large OBject(字元大物件)

其它…………………

 

     2、建立表語句

create table t_student(
	no int(10) not null unique,
	name varchar(32),
	sex char(2),
	birth date,
	email varchar(128)
	);

    注:表格的名字最好以t_或者 tbl_開始,增強可讀性

    3、 刪除表語句

 drop table if exists  t_student;

   4、 健表加約束  constraint

               常見約束:

                   i1、非空約束,not null

                   i2、唯一約束 ,unique     (不能為空和唯一性的約束可以同時加在同一個欄位上,上面在建立表的時候已經演示了)

                   i3、主鍵約束 、primary key

                   i4、外來鍵約束、foreign key

            a)  not null、unique

                   // 使用表級約束給多欄位聯合新增約束

drop table if exists t_user;
	create table t_user(
		id int(10),
		name varchar(32) not null,
		email varchar(128),
		unique(name,email)  ##這裡使用name和email共同決定了它的唯一性
		);

         b) primary key 和 foreign key

            primary key:給某個欄位新增主鍵約束primary key之後,該欄位不能重複,並且不能為空,主欄位還會預設新增“索引-index”

       建立主鍵

drop table if exists t_classes;

create table t_classes(

         classes_id int(3),

         classes_name varchar(40),

         constraint pk_classes_id primary key(classes_id)

)

     建立外來鍵

drop table if exists t_student;

create table t_student(

         student_id     int(10),

         student_name        varchar(20),

         sex            char(2),

         birthday   date,

         email                  varchar(30),

         classes_id         int(3),

         constraint      student_id_pk primary key(student_id),

         constraint  fk_classes_id   foreign  key(classes_id)  references  t_classes(classes_id)           

)

二、表的增、刪、改

       1、增

Insert into 表名(欄位,。。。。) values(值,………..)

       insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptnp) values(9997,'zhangsan','MANAGER','null','1981-06-12',3000,500,10);

     2、刪

Delete from表名 where 。。。。。

       delete from emp where comm = 500;          ##刪除津貼為500的員工資訊

   3、改

update 表名 set 欄位名稱1=需要修改的值1, 欄位名稱2=需要修改的值2 where …….

       update emp set sal = sal*1.1 where job  = 'MANAGER';