日期:2014-05-16  浏览次数:20794 次

我的复习--Mysql DDL语句
Mysql的学习笔记
1 常用命令
查看mysql上有多少个数据库  show databases;

使用数据库 use 数据库名;
显示数据库内的表 show tables;

创建数据库 create database 数据库名;
查看表结构  desc表名

删除数据库
drop database 数据库名

数据库的DDL --》操作数据库对象的语句,包括创建create 删除drop 修改 alter 数据库对象

创建表
普通方法
create table test(test_id int,
test_price decimal,
test_name varchar(255) default 'xxx',
test_desc text,
test_img blob,
test_date datetime);
  通过自查询的方法
create table test2 as select * from test;
修改表
   添加表字段
alter table test2 add(age int);
   修改字段的类型
我们先添加一列 haha_id
alter table test2 add haha_id varchar(255);
现在在修改haha_id的类型
alter table test2 modify haha_id int;
   删除列
alter table test2 drop haha_id;
   删除表的语法
drop table 表名
drop table test2;
   删除整个表的记录 truncate 表名
truncate test2;   这个是delete的豪华升级版直接就删除了整个表的数据但是对表的结构还是

已于保留。

建立约束
create primary_test(
test_id int primary key,
test_name varchar(255)

);
建表示创建表级别的主键约束
create primary_test2(

test_id int not null,
test_name varchar(255),
test_pass varchar(255),
constraint test2_pk primary key(test_id)
);
创建表时 建多列组合的主键约束
create table primary_test3(
test_id int not null,
test_name varchar(255),
test_pass varchar(255),
constraint test3_pk primary key(test_id,test_pass)
);
删除主键约束
alter table primary_test3 drop primary key;
指定表添加主键约束
alter table primary_test4 add primary key(test_id);
设置主键自增涨
create table primary_test4(
test_id int auto_increment primary key,
test_name varchar(255)
);
创建外键约束
教师---学生表 看成简单的一对多的关系
create table teacher_table(
teacher_id int auto_increment primary key,
teacher_name varchar(255)
);
create table student_table(
student_id int auto_increment primary key,
stidemt_name varchar(255),
teacher_id int,
foreign key(teacher_id) references teacher_table(teacher_id)
);[/b][/size][/size]