简体   繁体   English

复杂查询-MySql(类别x产品)

[英]Complex Query - MySql (Categories x Products)

I have difficult about a complex query. 我很难处理复杂的查询。 There is a table for categories and for products. 有一个类别和产品表。 I need show 4 products of each category. 我需要显示每个类别的4个产品。 How can I do that? 我怎样才能做到这一点?

My struct: Category.id, Category.name and Product.id, Product.category_id. 我的结构:Category.id,Category.name和Product.id,Product.category_id。

SQL: SQL:

SELECT Product.id, Product.name, Product.img, Category.name FROM categories AS Category
INNER JOIN (SELECT Product.id, Product.name, Product.img, Product.category_id FROM products AS Product) AS Product ON
Product.category_id = Category.id;

Where do I put the limits for products? 我在哪里设置产品限制?

Thanks. 谢谢。

Felipe Marques 费利佩·马克斯

This is painful in MySQL (in my opinion). 在我看来,这在MySQL中很痛苦。 Here is a version with a correlated subquery: 这是带有相关子查询的版本:

SELECT p.id, p.name, p.img, c.name
FROM categories c INNER JOIN
     (SELECT p.id, p.name, p.img, p.category_id,
             (select count(*) from products p2 where p2.category_id = p.category_id and p2.id <= p.id
             ) as seqnum
      FROM products p
     ) p
     ON Product.category_id = Category.id
where seqnum <= 4

This uses the correlated subquery to count the number of products who product id is less than or equal to the given product. 这使用相关子查询来计算产品ID小于或等于给定产品的产品数量。 This creates a sequence number, where you can select the first four. 这将创建一个序列号,您可以在其中选择前四个。

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

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