mysql 根据字段分组且按顺序码取前3名sql

  • Post author:
  • Post category:mysql


实现方式:利用rank排序查询

SELECT

a.id,

a.cinema_id,

a.cinema_name,

a.mer_name,

seq

FROM

(

SELECT

merchandise.*,

IF

( @last_cinema_id = cinema_id, @rank := @rank + 1, @rank := 1 ) AS “rank”,

@last_cinema_id := cinema_id

FROM

merchandise,(

SELECT

@rank := 0,

@last_cinema_id := “”

) r

ORDER BY

cinema_id,  #排序字段

seq DESC   #排序字段

) a

WHERE

rank <= 3   #取前几名

order by a.cinema_name



版权声明:本文为weixin_41943486原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。