查看、管理表结构
use onlinedb使用数据库
show tables;查看存在的表
desc users;查看表结构
show columns from users;查看表结构
修改数据表
alter table good rename instance;修改表名
alter table users add gcomddition varchar(34) after uregtime ;修改字段的排列位置
alter table users drop gcomddition;删除字段
复制数据表
create table temp1 select * from users;复制表结构及数据到新表
create table temp2 select*from users where false;只复制表结构到新表,条件恒为false
create table temp3 like users;源表约束一同复制
create table temp4 as (select ulogin,uname from users);复制表的部分字段到新表
drop table temp1,temp2,temp3,temp4;删除数据表
实现数据的完整性 (添加约束)
desc goods;
select *from goods;
alter table goods add constraint ck_gprice check(gprice>=0);添加check约束
alter table goods add constraint fk_goods_cid foreign key(cid) references category(cid);外键添加
建立 foreign key约束的数据表,其存储引擎必须时 InnoDB,且该表不能为临时表
show create table goods; 查看以下数据结构
CREATE TABLE `goods` (
`gid` int NOT NULL AUTO_INCREMENT COMMENT '商品ID',
`cid` int NOT NULL COMMENT '类别ID,外键',
`gcode` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商品编号',
`gname` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商品名称',
`gprice` decimal(20,2) NOT NULL DEFAULT '0.00' COMMENT '商品价格',
`gquantity` int DEFAULT '0' COMMENT '库存量',
`gsale_qty` int NOT NULL DEFAULT '0' COMMENT '销售量',
`gaddtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上架时间',
`gishot` tinyint DEFAULT '0' COMMENT '是否热销',
`gimage` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '商品图片',
PRIMARY KEY (`gid`) USING BTREE,
KEY `fk_goods_cid` (`cid`),
CONSTRAINT `fk_goods_cid` FOREIGN KEY (`cid`) REFERENCES `category` (`cid`),
CONSTRAINT `ck_gprice` CHECK ((`gprice` >= 0))
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC
alter table goods drop foreign key fk_goods_cid;删除外键约束
alter table goods drop check ck_gprice;删除 check 约束
show create table goods;
CREATE TABLE `goods` (
`gid` int NOT NULL AUTO_INCREMENT COMMENT '商品ID',
`cid` int NOT NULL COMMENT '类别ID,外键',
`gcode` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商品编号',
`gname` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商品名称',
`gprice` decimal(20,2) NOT NULL DEFAULT '0.00' COMMENT '商品价格',
`gquantity` int DEFAULT '0' COMMENT '库存量',
`gsale_qty` int NOT NULL DEFAULT '0' COMMENT '销售量',
`gaddtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上架时间',
`gishot` tinyint DEFAULT '0' COMMENT '是否热销',
`gimage` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '商品图片',
PRIMARY KEY (`gid`) USING BTREE,
KEY `fk_goods_cid` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC