简体   繁体   中英

How to write SQL Query (Get all Categories and get 10 Products on each Category)

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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