【SQL基本语法 二】DDL数据定义语句

创建表的语法

1,普通建表方式
	create table [模式名.] 表名  
	(#可以有多个列定义
	columnName1  datetype[default expr],
	columnName2  datetype[default expr],
	………………
	)     
    ***普通建表方式,建的只是空表,上述部分为建表语法***
    create table test
       (  #整型通常用int                                               
	     test_id int,                    //每个列定义之间以英文逗号隔开
	    #小数点儿数
	     test_price  decimal,
	  #普通长度文本,使用default 指定默认值
	    test_name  varchar(255) default 'XXX',
	  #大文本类型
	    test_desc  text,
	  #图片
	     test_img blob,
	  test_date datetime
	);

2,子查询建表方式
	create table [模式名.] 表名    [column[,column…]]         //使用子查询语句建表,可以在建表的同时插入数据
	as
          subquery;  
	*****上述为子查询建表语法,注意:新表的字段列表必须与子查询中字段列表相同*****    
	#创建hehe数据表,该数据表和user_inf完全相同,数据也完全相同
	create table hehe
	as
	select*from   user_inf;                       //以上方式为省略字段列表,新表的数据和字段与之前的完全相同 

修改表结构的语法

 1,增加列定义
	alter table  表名
	add
	(
	    #可以有多个列定义
	    column_name1 datatype[default exper],                               //如果只是新增一列,则可以省略圆括号,仅在add后面跟一个列定义即可
	  ..  
	);                                                                                      
	****************************************************     //增加列的语法
	#为hehe增加一个hehe_id字段,该字段类型为int
	alter table hehe
	add hehe_id   int;
	#为hehe数据表增加aaa、bbb字段,两个字段类型都为varchar(255)
	alter table hehe
	add
	(
	   aaa varchar default 'xxx',
	   bbb varchar(255)
	);
 2,修改列定义(数据类型)
	alter table 表名
	modify column_name datatype  [default exper]  [first|after col_name];          //first|after col_name表名指定将目标修改到指定位置
	*********************************************************  //修改列语法
	#将hehe表的hehe_id列修改成varchar(255)类型
	alter table hehe
	modify hehe_id vachar(255);
	#将heh表中的bbb列修改成int类型
	alter table hehe
	modify hehe bbb int;       //注意,mysql不支持一次修改多列,如果删除已有数据记录,容易失败,如果修改默认值,只会对以 后的插入操作有作用,对已存数据不会有影响                                                
3,删除列
	alter table 表名
	drop column_name
	*********************************************************  //删除列语法
	删除列只需在drop后面紧跟列名即可
	#删除hehe表中的aaa字段
	alter table hehe
	drop aaa;;
4,重命名表
	alter table 表名
	rename  to  新表名
	*********************************************************  //重命名表语法
	alter table hehe
	rename to TML;
5,改变列名,同时修改数据类型
	alter table 表名
	change old_column_name   new_column_name    type  [default exper]  [first|after col_name]; 
	*********************************************************  //重命名列语法
	alter table TML
	change bbb ddd int

删除表的语法

    drop  table  表名;
	*********************************************************  //删除表语法
     #删除数据表
     drop table TML;       //该表结构被删除,对象被删除,所有数据被删除,所有相关索引,约束被删除
     *********************************************************  //删除表数据语法
     truncate表
    truncate 表名    //truncate的作用是截断某表,具体作用是删除表的数据而不删除表的结构

猜你喜欢

转载自blog.csdn.net/sinat_33087001/article/details/107654304
今日推荐