gpt4 book ai didi

mysql - 使多对多关系的查询量保持不变

转载 作者:行者123 更新时间:2023-11-29 03:18:17 24 4
gpt4 key购买 nike

我有一个具有 2 个多对多关系的实体:
Product,它可以有很多类别和很多标签。一个标签或一个类别也可以有很多产品。

现在的架构是:

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 |
| |
-------------------------------------------------------

最佳答案

你可以试试这个(它依次使用标签和类别的连接,并通过列 table_type 区分它们):

select *, 'CAT' as table_type
from products p left join products_categories pc left join categories c
ON p.product_id = pc.product_id and pc.category_id = c.category_id
UNION ALL
select *, 'TAG' as table_type
from products p left join products_tags pt left join tags t
ON p.product_id = pt.product_id and pt.tag_id = t.tag_id
order by p.product_id

关于mysql - 使多对多关系的查询量保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50555422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com