Digital Pros
Digital Pros

Reputation: 39

mysql query products and all categories for that product

Ok I have 3 tables that I am working with

products
id
name
description
url_slug

categories
id
name
url_slug

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"
category 1, category 2, category 3 "and each category links to that category"

Product 2 "links to the product page"
category 3, category 7 "and each category links to that category"

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.

I would like do accomplish this with one query and just loop through.

Any help is much appreciated!!

Upvotes: 0

Views: 957

Answers (1)

Barmar
Barmar

Reputation: 780724

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.

Upvotes: 0

Related Questions