1
votes

I am very new to Database and I want to know raw sql query. I have 2 tables Category and Product Product table has foreign_key(category_id).

How can I get all categories with 10 products for each category? So I will display each category name and 10 products on first page.

SELECT *
FROM categories
INNER JOIN
(SELECT * FROM products ORDER BY price LIMIT 10) as p
ON
 categories.id = p.category_id

And also want to query reviews table that product has. How can I join 2 tables(Category with Product(1), Review(2)

1

1 Answers

2
votes

A simple way is a lateral join:

SELECT *
FROM categories c LEFT JOIN LATERAL
     (SELECT p.*
      FROM products p
      WHERE c.id = p.category_id
      ORDER_BY p.price
      LIMIT 10
     ) p
     ON 1 = 1