简体   繁体   English

mysql 查询产品和该产品的所有类别

[英]mysql query products and all categories for that product

Ok I have 3 tables that I am working with好的,我正在使用 3 张桌子

products产品
id ID
name姓名
description描述
url_slug url_slug

categories类别
id ID
name姓名
url_slug url_slug

products_to_categories products_to_categories
product_id产品编号
category_id类别编号

I have a page that you can go to and view all the newest products.我有一个页面,您可以访问并查看所有最新产品。 Doesn't matter what category it's in just that it is new.它属于什么类别并不重要,因为它是新的。

I display the products like this我像这样展示产品

Product 1 "links to the product page"产品 1“产品页面链接”
category 1, category 2, category 3 "and each category links to that category"第 1 类、第 2 类、第 3 类“以及每个类别链接到该类别”

Product 2 "links to the product page"产品 2“产品页面链接”
category 3, category 7 "and each category links to that category"第 3 类、第 7 类“以及每个类别链接到该类别”

To accomplish this I currently query the latest products为此,我目前查询最新产品
Loop through them and for each product I do a query that gets all the categories that product is in.循环遍历它们,对于每个产品,我都会进行查询以获取产品所在的所有类别。

It works but if you are list 100 or 200 products at a time that 201 querys for 1 page load.它有效,但如果您一次列出 100 或 200 个产品,则 201 查询 1 个页面加载。

I would like do accomplish this with one query and just loop through.我想用一个查询来完成这一点,然后循环遍历。

Any help is much appreciated!!任何帮助深表感谢!!

Use a JOIN:使用连接:

SELECT p.name AS product_name, p.id AS product_id,
       c.name AS category_name, c.id AS category_id
FROM products AS p
JOIN product_categories AS pc ON p.id = pc.product_id
JOIN categories AS c ON c.id = pc.category_id
ORDER BY product_id, category_id

Loop through the results, and print the Product header whenever it changes, then print the category information for each row.循环遍历结果,并在Product标题发生变化时打印它,然后打印每一行的类别信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM