您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2025/11/12 13:46:14发布35次查看
想表达的意思:用户有很多属性(tag),比如唱歌、跳舞、玩游戏,表结构如下图:
创建表的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);

我想在页面表现如下:
首先是用户列表,但同时把用户的tag都带出来。
最终的表现形式和segmentfault的首页列表很像,显示问题列表并顺便把问题的很多tag也显示出来。
目前我有两种办法:
先把用户select出来,然后在php中循环用户的结果集,再select出属性。通过join连表,查出如下的记录,然后再显示的时候过滤。请教有没有其他的方案?
谢谢。
回复内容: 想表达的意思:用户有很多属性(tag),比如唱歌、跳舞、玩游戏,表结构如下图:
创建表的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);

我想在页面表现如下:
首先是用户列表,但同时把用户的tag都带出来。
最终的表现形式和segmentfault的首页列表很像,显示问题列表并顺便把问题的很多tag也显示出来。
目前我有两种办法:
先把用户select出来,然后在php中循环用户的结果集,再select出属性。通过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 ...
这是一个多对多关系把??
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product