2015/09/16

mysql关系表使用


在使用mysql时,我们经常会遇到不同表之间的关系处理,一对多,多对多,这就是关系表的研究过程。例如:

有一个玩家表user: 玩家唯一id, 名称, 性别

create table if not exists user(
userid bigint not null,
name varchar(15),
sex tinyint,
primary key(userid));

有一个道具表item: 道具唯一id,道具名称,道具价格,道具稀有度

create table if not exists item(
itemid bigint not null,
name varchar(15),
price int,
rare int,
primary key(itemid));

一个玩家肯定不止有一个道具,玩家身上可能有上百个道具,这就是一对多的关系存在,那么我们怎样才能通过玩家id(userid)来获取属于他的所有道具呢?这时我们就用到了关系表。


方法一:

直接在 多方 的表中加一列 一方 的唯一id,既上面的item表应该修改为:

create table if not exists item(
itemid bigint not null,
userid bigint not null,
name varchar(15),
price int,
rare int,
primary key(itemid,userid));

把userid添加进item表中,并且也将它设置为主key,so,我们要查找属于玩家id(101)的所有道具时,使用的mysql语句:

select * from item where userid=101;

方法二:

创建一个中间表来维护两表之间的关系,这也是多对多的常用法

create table if not exists relation(
id bigint not null auto_increment,
itemid bigint not null,
userid bigint not null,
primary key(id));

这样我们给玩家每增加一个道具时,需要将它们的关系加到relation中。假设给玩家(101)添加一个雪莲道具:

insert into item(itemid,name,price,rare) value (1001,"雪莲",20000,5);
insert into relation(itemid,userid) value (1001,101);

现在我们要查找属于玩家id(userid)的所有道具时,使用的mysql语句:

select * from relation
left join user on relation.userid = user.userid
left join item on relation.itemid = item.itemid
where user.userid=101;

或者只显示user和item数据:

select user.*,item.* from relation
left join user on relation.userid = user.userid
left join item on relation.itemid = item.itemid
where user.userid=101;

或者只显示item数据:

select item.* from relation
left join item on relation.itemid = item.itemid
where relation.userid=101;

最后感谢 CodeIgniter 中国1号 群里的大神 天意²º¹³ 给我的大力帮助