【mysql】在MYSQL中一对多表关系这样显示,最优的做法是什么?

想表达的意思:用户有很多属性(Tag),比如唱歌、跳舞、玩游戏,表结构如下图:【mysql】在MYSQL中一对多表关系这样显示,最优的做法是什么?
创建表的mysql语句如下:

drop table if exists user;

create table user

(

user_id int not null auto_increment,

user_name varchar(20),

primary key (user_id)

);

drop table if exists tags;

create table tags

(

tag_id int not null auto_increment,

tag_name varchar(100),

primary key (tag_id)

);

drop table if exists user_tag;

create table user_tag

(

user_id int,

tag_id int

);

插入数据的SQL语句如下:

insert into user values(1,'小A');

insert into user values(2,'小B');

insert into user values(3,'小C');

insert into tags values(1,'唱歌');

insert into tags values(2,'跳舞');

insert into tags values(3,'宅');

insert into tags values(4,'看书');

insert into tags values(5,'旅游');

insert into user_tag values(1,1);

insert into user_tag values(1,2);

insert into user_tag values(2,1);

insert into user_tag values(3,1);

insert into user_tag values(3,4);

insert into user_tag values(3,5);

我想在页面表现如下:
【mysql】在MYSQL中一对多表关系这样显示,最优的做法是什么?

首先是用户列表,但同时把用户的tag都带出来。

最终的表现形式和segmentfault的首页列表很像,显示问题列表并顺便把问题的很多tag也显示出来。

目前我有两种办法:

  1. 先把用户select出来,然后在php中循环用户的结果集,再select出属性。
  2. 通过join连表,查出如下的记录,然后再显示的时候过滤。

请教有没有其他的方案?

谢谢。

回答

如果数据量不大,那么使用left join 即可,很多企业级的产品基本采用这种方式。

如果数据量比较大,那么需要采用冷热数据,热数据把uid uname tag_name这放到缓存中,冷数据采用多个简单查询方式。

你说的两种方法里的1比较好,很多网站也是这么做的。

但是有一点,就是user_tag表要做一层缓存,让全部的这种user-tag的查询都到内存中进行。

if you don't need to lookup users by tag, i will simply put all of them into one table. managing user_tag will be a pain later on. it will also be easier if you have a max on the number of tags a user can have ...

这是一个多对多关系把??

以上是 【mysql】在MYSQL中一对多表关系这样显示,最优的做法是什么? 的全部内容, 来源链接: utcz.com/a/72890.html

回到顶部