本教程中所使用的数据库的建表语句都在“SQL教程——索引”这篇文章中,点击链接直达:索引&建表语句
摘要:本文主要介绍SQL的DDL语法
表的管理
1、表的创建
语法:
create table 表名(
列名 列的类型【(长度)约束】,
列名 列的类型【(长度)约束】,
列名 列的类型【(长度)约束】,
)
#案例: 创建表Book
creat table book(
id int, #编号
bname varhcar(20); #图书名
price double, #价格
author varchar(20), #作者
publishDate DATETIME #出版日期
);
2、表的修改
语法:
alter table 表名 add|drop|modify|change column 列名【列类型 约束】;
-
修改列名
alter table book change column publishdate pubDate datetime;
-
修改列的类型或约束
alter table book modify column pybdate timestamp
-
添加新列
alter table book add column annual double
-
删除列
alter table drop column annual;
-
修改表名
alter table author rename to book_author;
3、表的删除
drop table if exists book_author;
show tables;
#通用的写法
drop database if exists 旧库名;
create database 新库名;
4、表的复制
insert into author values(1, '村上春树', '日本'),
(2, '莫言', '中国'),
(3, '冯唐', '中国');
#1.仅仅复制表的结构
create table copy like author;
#2.复制表的结构+数据
create table copy2
select * from author;
#3.只复制部分数据
create table copy3
select id, au_name
from author
where nation = '中国';
#4.仅仅复制某些字段
create table copy
select id, au_name
from author
where 0;