mysql学习4

技术分析:

1.多表之间的关系如何维护

外键约束:foreign key

给product表中的这个cno添加一个外键约束

alter  table product add foreign key(cno) references category(cid);【添加外键约束的时候要确保表内所有数据都可以被约束】

2.& 建库原则&多表之间的建表原则

建库原则:一个项目/应用建立一个数据库

多表之间的建表原则:

一对多:

   建表原则:在多的一方添加一个外键指向一的一方的主键

多对多:

   建表原则:多建一张中间表,将多对多变成一对多,至少要有俩个外键,这俩个外键分别指向原来的那张表                                                                                                

一对一:

  建表原则:将一对一的情况,当做一对多情况处理,在任意一张表添加一个外键,并且这个外键要唯一,指向另一张表;直接将俩张表合成一张;将俩张表主键建立起连接,让俩张表主键相等

 

建立day11库用来存放商城表单,模拟操作

建立用户表

create table user(
uid int primary key auto_increment,
username varchar(31),
passward varchar(31),
phone varchar(11)
);

插入用户信息

insert into user values(1,'zhangsan','123','1123245555');

创建订单表

create table orders(

oid int primary key auto_increment,

sum int not null,

otime timestamp,

address varchar(100),

uno int ,

foreign key(uno) references user(uid)

);

 插入订单

insert into orders values(1,200,null,'黑马前台',1);

insert into orders values(2,300,null,'黑马hou台',1);

 商品表

create table product(

pid int primary key auto_increment,

paname varchar(30),

price double,

cno int,

foreign key(cno) references category(cid)

);

插入商品数据

insert into product values(null,'小米mix4',999,1);

insert into product values(null,'Apple',1999,1);

insert into product values(null,'阿迪',233,2);

insert into product values(null,'玉溪',19,3);

insert into product values(nul,'娃哈哈',9,4);

insert into product values(null,'五香瓜子',5,5);

 

商品分类表

create table category(

cid int primary key auto_increment,

cname varchar(15),

cdesc varchar(100)

);

插入商品分类数据

insert into category values(null,'手机数码','电子产品');

insert into category values(null,'鞋靴箱包','江南皮革厂');

insert into category values(null,'香烟酒水','黄鹤楼二锅头');

insert into category values(null,'酸奶饼干','娃哈哈 优酸乳');

insert into category values(null,'零食','瓜子花生八宝粥');

 订单项

create table orderitem(

ono int,

pno int,

foreign key(ono) references orders(oid);

foreign key(pno) references product(pid);

ocount int,

subsum double

);

累了 不写了 骂的 各种报错

posted @ 2021-01-09 17:30  渊祭  阅读(66)  评论(0)    收藏  举报