简体   繁体   English

根据mysql查询中的外键值获取特定类别的2条记录?

[英]Get 2 record of a particular category based on foreignkey value in mysql query?

I have two table product and mastercategory我有两个表productmastercategory

product has columns产品有列

id - pk, 
title- varchar,
price - varchar,
selling_price - varchar, 
description - varchar, 
is_approved - bool,
is_live - bool,
is_visible - bool,
category_id - fk (foreign_key of category table)

mastercategory has columns mastercategory 有列

id - pk, 
name - varchar, 
is_active - bool,
is_hotcategory - bool,

I want to get 2 latest record of each category where is_hotcategory is true我想获得is_hotcategorytrue的每个类别的 2 条最新记录

How can I get this我怎样才能得到这个

I tried it with this:我用这个试过:

select cp.id,cp.title, cp.category_id from product cp 
left join mastercategory cmc on cp.category_id = cmc.id where cmc.is_hotcategory = 1 and cp.id in (
select max(cp.id) As id
from product cp 
where cp.is_visible = 1 and cp.is_live= 1 and cp.is_approved=1 
group by category_id 

union all

select max(cp.id) As id
from product cp 
left join mastercategory cmc on cp.category_id = cmc.id 
where cmc.is_hotcategory = 1 and 
cp.is_visible = 1 and cp.is_live= 1 and cp.is_approved=1 and
(cp.id not in (select max(cp.id) 
from product cp 
where cp.is_visible = 1 and cp.is_live= 1 and cp.is_approved=1 group by category_id )) group by category_id 
) order by category_id asc;

I'm getting last record of each category then getting 2nd last record of each category then with union combining both the search query我得到每个类别的最后一条记录,然后得到每个类别的第二条最后一条记录,然后结合两个搜索查询

I think it will work but what if I have to get more than 2 record of each category.我认为它会起作用,但如果我必须获得每个类别的 2 条以上记录怎么办。 Is there any other solution to that.有没有其他解决方案。

WITH cte AS (
    select cp.id, cp.title, cp.category_id,
           ROW_NUMBER() OVER (PARTITION BY cp.category_id ORDER BY cp.id DESC) rn
    from product cp 
    join mastercategory cmc on cp.category_id = cmc.id 
    where cmc.is_hotcategory
      and cp.is_visible
      and cp.is_live
      and cp.is_approved 
)
SELECT *
FROM cte
WHERE rn < 3;

I assume that "latest record of each category" is the product row with greatest id from the rows with the same category_id (I have not found a column similar to created_at ).我假设“每个类别的最新记录”是具有相同category_id的行中id最大的产品行(我还没有找到类似于created_at的列)。 If not then adjust frame specification accordingly.如果不是,则相应地调整框架规格。

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

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