比方说,我有三个表(MySQL),一个用于用户,一个用于标记,最后一个用于加入它们(多对多关系):在一个查询中获取行及其外键行与许多查询
create table user_tag(
user_id int unsigned not null,
tag_id int unsigned not null,
primary_key (user_id, tag_id)
);
我想从数据库中获取完整的用户列表(或至少其中很多)以及他们关联的标签。我使用PHP作为服务器语言。
所以我的问题是,是能够更好地执行一个SQL查询获取所有的信息是这样的:
select user.name, user.image, ..., tag.name from user, tag, user_tag
where user.user_id = user_tag.user_id and tag.tag_id = user_tag.tag_id;
或者是它更好地为用户执行一个第一查询和事后获取他们的标签:
select user.name, user.image, ... from user;
,然后为每个用户:
select tag.name from tag, user_tag where tag.tag_id = user_tag.tag_id
and user_tag.user_id = $USERID;
我觉得第二是更好的选择,但恐怕对数据库的查询可能太多(注意,这是一个通用的设计示例,但此模式可以在具有不同表格的数据库中多次出现)。
哪个更好?优点和缺点?其他方法?
感谢
PS:请不要考虑SQL语法,我没有检查出来对一个真正的数据库,它是唯一的设计问题,谢谢大家
可能重复[JOIN查询vs多个查询](http://stackoverflow.com/questions/1067016/join-queries-vs-multiple-queries) – ManseUK