简体   繁体   English

如何使用联合表限制子查询 [MySQL]

[英]How can I limit a subquery [MySQL] with union table

I have following tables:我有以下表格:

  • product_category (union table) product_category_id (PK AI) product_id category_id product_category (联合表) product_category_id (PK AI) product_id category_id

  • categories category_id (PK AI) title...etc类别category_id (PK AI) 标题...等

  • products product_id (PK AI) title order etc...产品product_id(PK AI)标题顺序等...

I want get all categories with their associated products by union table (product_category) and limit their products to 5 per category, basically an many-to-many relationship, like netflix categories carousel (drama category have 5 associated movies and terror category have 5 associated movies etc...) I've tried this but join is not working as I expected:我想通过联合表(product_category)获取所有类别及其相关产品,并将其产品限制为每个类别 5 个,基本上是多对多关系,如 netflix 类别轮播(戏剧类别有 5 个相关电影,恐怖类别有 5 个相关电影等...)我已经尝试过,但加入没有按我预期的那样工作:

SELECT 
*
FROM
product_category AS pc
    INNER JOIN
categories AS cat ON cat.category_id = pc.category_id
    INNER JOIN
(SELECT 
    *
FROM
    products
LIMIT 1 ORDER BY products.order DESC) AS x ON x.product_id = pc.product_id;

So... ¿How can I limit products per category?所以... ¿如何限制每个类别的产品? i'am using MySQL 5.7 I dont want to query multiple times the database to get manually products by category, I want do the job by the cleanest way with only query or two at most.我正在使用 MySQL 5.7 我不想多次查询数据库以按类别手动获取产品,我想以最干净的方式完成工作,最多只查询一两个。 ¿It is posible? ¿ 这可能吗?

Regards.问候。

On MySQL 5.7, you may try something along these lines, using an inner join to restrict to products with the most recent order value:在 MySQL 5.7 上,您可以尝试以下方式,使用内部连接来限制具有最新order价值的产品:

SELECT *
FROM product_category AS pc
INNER JOIN categories AS cat ON cat.category_id = pc.category_id
INNER JOIN products AS p ON p.product_id = pc.product_id
INNER JOIN
(
    SELECT product_id, MAX(`order`) AS latest_order
    FROM products
    GROUP BY product_id
) p2
    ON p2.product_id = p.product_id AND
       p2.latest_order = p.`order`;

The join to the subquery aliased as p2 above restricts to only product records having the latest order value.与上面别名为p2的子查询的连接仅限于具有最新order值的产品记录。 Side note: Please avoid naming your columns ORDER , which is a reserved MySQL keyword.旁注:请避免命名您的列ORDER ,这是一个保留的 MySQL 关键字。

Edit: A solution for top 5 products per order, ordered by most recent first, using ROW_NUMBER :编辑:每个订单前 5 个产品的解决方案,由最近的第一个订购,使用ROW_NUMBER

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY p.product_id ORDER BY `order` DESC) rn
    FROM product_category AS pc
    INNER JOIN categories AS cat ON cat.category_id = pc.category_id
    INNER JOIN products AS p ON p.product_id = pc.product_id
)

SELECT *
FROM cte
WHERE rn <= 5;

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

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