【发布时间】:2012-01-09 12:42:12
【问题描述】:
假设我有三张表(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语法,我没有根据真实数据库检查过,这只是设计问题,谢谢
【问题讨论】:
标签: php mysql database foreign-keys