mysql每个类型查三条_MySQL查询:从表中为每个类别选择前3行

bd96500e110b49cbb3cd949968f18be7.png

I have a table with records and it has a row called category. I have inserted too many articles and I want to select only two articles from each category.

I tried to do something like this:

I created a view:

CREATE VIEW limitrows AS

SELECT * FROM tbl_artikujt ORDER BY articleid DESC LIMIT 2

Then I created this query:

SELECT *

FROM tbl_artikujt

WHERE

artikullid IN

(

SELECT artikullid

FROM limitrows

ORDER BY category DESC

)

ORDER BY category DESC;

But this is not working and is giving me only two records?

解决方案

LIMIT only stops the number of results the statement returns. What you're looking for is generally called analytic/windowing/ranking functions - which MySQL doesn't support but you can emulate using variables:

SELECT x.*

FROM (SELECT t.*,

CASE

WHEN @category != t.category THEN @rownum := 1

ELSE @rownum := @rownum + 1

END AS rank,

@category := t.category AS var_category

FROM TBL_ARTIKUJT t

JOIN (SELECT @rownum := NULL, @category := '') r

ORDER BY t.category) x

WHERE x.rank <= 3

If you don't change SELECT x.*, the result set will include the rank and var_category values - you'll have to specify the columns you really want if this isn't the case.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值