我的查询: -
SELECT
p.*,
b.brand_name
FROM
portfolio p,
branding_category b
WHERE
p.category = 'BRANDING'
AND
p.brand_category = b.id
AND
is_active = '1'
GROUP BY
p.brand_category
ORDER BY p.id DESC
LIMIT 10
假设投资组合表有: -
id category brand_category is_active title
1 test 8 1 abc
2 test 7 1 pqr
3 test 8 1 xyz
4 test 7 1 ijk
我想显示输出: - 也就是说,应该返回每组中的最后一条记录。
id category brand_name is_active title
3 test Catalogs 1 xyz
4 test Posters 1 ijk
修改: -
branding_category
id brand_name
8 Catalogs
7 Posters
即每组的最后一行。请帮帮我。我知道它存在于stackoverflow Retrieving the last record in each group中,但我无法为两个表写。
答案 0 :(得分:0)
试试这个: -
SELECT p.*,b.brand_name
FROM portfolio p
INNER JOIN branding_category b ON p.brand_category = b.id
INNER JOIN (
SELECT MAX(id) MaxMsgIDForThread
FROM portfolio
WHERE is_active = '1'
GROUP BY brand_category
) g ON p.id = g.MaxMsgIDForThread
Order by p.id Desc
LIMIT 10
答案 1 :(得分:-2)
试试这个,
select x.id,x.category,x.brand_name,x.is_active,x.title from (
select
p.id,p.category,pc.brand_name,p.is_active,p.title,
ROW_NUMBER()over ( ORDER BY p.id) as Rnk
from portfolio p inner join branding_category pc
on p.brand_category=pc.id
) x where Rnk >2