mysql排序和排名声明

时间:2011-08-14 12:52:18

标签: mysql

我在mysql语句中需要一些帮助 Ive table1有7列,表2有8列额外列名为ranking,我的语句应该是这样的 从表1中选择全部然后按“用户数量”对其进行排序,将其插入表2并排名开始1 2 3等,

table 1 : 
username |     email         | number of users
jack          a@a.com               75
ralf          b@b.com               200
anne          c@c.com                12
sonny         d@d.com                300

===================================

这里我需要根据用户数量进行INSERT和RANKING

table 2 

ranking    | username |     email         | number of users
1
2
3

3 个答案:

答案 0 :(得分:2)

我会避免使用另一张桌子。单个查询就足够了。

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:=@r+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)

这是一个考虑关系的更智能的版本

select @r:=@r + 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 :(得分:1)

INSERT INTO table2
  SELECT @rank := @rank + 1, table1.* FROM table1
  JOIN( SELECT @rank := 0 ) AS init
  ORDER BY number_of_users DESC

答案 2 :(得分:0)

你需要做这样的事情:

SELECT * FROM `table1`
INNER JOIN `table2` USING ([a common filed name here])
ORDER BY table2.[the filed name here]

祝你好运!