sql >> Databasteknik >  >> RDS >> Mysql

mysql sortering och rangordning uttalande

Jag skulle undvika att använda ett annat bord. En enda fråga räcker.

create table mytable (
id int not null auto_increment primary key,
username varchar(50),
email varchar(50),
number int
) engine = myisam;

insert into mytable (username,email,number)
values 
('a','aaa',10),
('b','bbb',30),
('c','ccc',50),
('d','ddd',30),
('e','eee',20),
('f','fff',45),
('g','ggg',20);

select @r:[email protected]+1 as rnk,username,email,number
from mytable,(select @r:=0) as r order by number desc

+------+----------+-------+--------+
| rnk  | username | email | number |
+------+----------+-------+--------+
|    1 | c        | ccc   |     50 |
|    2 | f        | fff   |     45 |
|    3 | b        | bbb   |     30 |
|    4 | d        | ddd   |     30 |
|    5 | e        | eee   |     20 |
|    6 | g        | ggg   |     20 |
|    7 | a        | aaa   |     10 |
+------+----------+-------+--------+
7 rows in set (0.00 sec)

Det här är en smartare version som överväger slipsar

select @r:[email protected] + 1 as rn, username,email,
@pos:= if(@previous<>number,@r,@pos) as position,
@previous:=number as num
from mytable,(select @r:=0,@pos:=0,@previuos:=0) as t order by number desc 

+------+----------+-------+----------+--------+
| rn   | username | email | position | num    |
+------+----------+-------+----------+--------+
|    1 | c        | ccc   |        1 |     50 |
|    2 | f        | fff   |        2 |     45 |
|    3 | b        | bbb   |        3 |     30 |
|    4 | d        | ddd   |        3 |     30 |
|    5 | e        | eee   |        5 |     20 |
|    6 | g        | ggg   |        5 |     20 |
|    7 | a        | aaa   |        7 |     10 |
+------+----------+-------+----------+--------+
7 rows in set (0.00 sec)


  1. Få LÄNGDEN av en LONG RAW

  2. Hur man laddar MySQL automatiskt vid start på OS X Yosemite / El Capitan

  3. MySQL binär lagring med BLOB VS OS filsystem:stora filer, stora kvantiteter, stora problem

  4. Få antalet dagar i en månad i PostgreSQL