我有一个实体,它有两个多对多关系:
还有Product
,它可以有很多类别和标签。一个Tag
或一个Category
也可以有许多产品。
现在的模式是:
products
-------------
product_id
name
categories
-------------
category_id
name
tags
-------------
tag_id
name
products_categories
-------------
product_id
category_id
products_tags
-------------
product_id
tag_id
我需要在一个单一的页面显示所有标签和类别的产品列表。
问题是我执行的查询数量是2n + 1
,其中n是页面中列出的产品数量。
基本上我首先要做的是:
select product_id, name from products
然后在我的应用程序中的一个循环中,我执行以下查询(使用伪代码):
tags = []
categories = []
for each product
tags[product_id] = select t.tag_id, t.name
from products_tags as pt
join tags t
on pt.tag_id = t.tag_id
where pt.product_id = {product_id}
categories[product_id] = select c.category_id, c.name
from products_categories as pc
join categories c
on pc.category = c.category_id
where pc.product_id = {product_id}
end for each
有没有一种好的方法可以使执行的查询的数量独立于查询的记录的数量?
编辑
对于每个产品,我需要以这种格式显示数据:
-------------------------------------------------------
| Product name: A good smartphone |
| Categories: Tech, Smartphone |
| Tags: smartphone, some-smartphone-brand, 4g |
| |
-------------------------------------------------------
https://stackoverflow.com/questions/50555422
复制相似问题