2014-06-27 23 views
1

我的用戶數據庫中有tbl_items,我想用特定的id(514)對特定項目的用戶排名進行排序。我有測試數據對我的開發環境與這組數據:如何在mysql中獲取這個特定的用戶排名查詢?

mysql> select * from tbl_items where classid=514; 
+---------+---------+----------+ 
| ownerId | classId | quantity | 
+---------+---------+----------+ 
|  1 |  514 |  3 | 
|  2 |  514 |  5 | 
|  3 |  514 |  11 | 
|  4 |  514 |  46 | 
|  5 |  514 |  57 | 
|  6 |  514 |  6 | 
|  7 |  514 |  3 | 
|  8 |  514 |  27 | 
|  10 |  514 |  2 | 
|  11 |  514 |  73 | 
|  12 |  514 |  18 | 
|  13 |  514 |  31 | 
+---------+---------+----------+ 
12 rows in set (0.00 sec) 

到目前爲止好:)我寫了下面的查詢:

set @row=0; 

select a.*, @row:[email protected]+1 as rank 
from (select a.ownerid,a.quantity from tbl_items a 
where a.classid=514) a order by quantity desc; 

+---------+----------+------+ 
| ownerid | quantity | rank | 
+---------+----------+------+ 
|  11 |  73 | 1 | 
|  5 |  57 | 2 | 
|  4 |  46 | 3 | 
|  13 |  31 | 4 | 
|  8 |  27 | 5 | 
|  12 |  18 | 6 | 
|  3 |  11 | 7 | 
|  6 |  6 | 8 | 
|  2 |  5 | 9 | 
|  7 |  3 | 10 | 
|  1 |  3 | 11 | 
|  10 |  2 | 12 | 
+---------+----------+------+ 
12 rows in set (0.00 sec) 

是正確行列的用戶。然而,在一個有很多記錄的表格中,我需要執行以下操作:

1)能夠得到列表的一小部分,用戶排名實際存在的位置,可以使我獲得周圍記錄的東西,保留總體排名: 我試圖通過設置用戶變量來設置當前用戶的排名,並使用偏移量和限制來做這些事情,但無法保持整體排名。

這應該讓我像以下(例如OWNERID = 2,環境限制5:

+---------+----------+------+ 
| ownerid | quantity | rank | 
+---------+----------+------+ 
|  3 |  11 | 7 | 
|  6 |  6 | 8 | 
|  2 |  5 | 9 | --> ownerId=2 
|  7 |  3 | 10 | 
|  1 |  3 | 11 | 
+---------+----------+------+ 
5 rows in set (0.00 sec) 

2)我還需要另外的查詢(最好是單查詢)是讓我的排名前3的位置+具有特定ID的特定用戶的排名,最好是單個查詢,無論他是否在前三名之內。我不能讓這個問題,以及

它看起來像下面的(例如OWNERID = 2再次):

+---------+----------+------+ 
| ownerid | quantity | rank | 
+---------+----------+------+ 
|  11 |  73 | 1 | 
|  5 |  57 | 2 | 
|  4 |  46 | 3 | 
|  2 |  5 | 9 | --> ownerId=2 
+---------+----------+------+ 
4 rows in set (0.00 sec) 

而且我是有點有關的性能關注在一張桌子上查詢有數百萬條記錄... 希望有人幫助:)

回答

1

1)圍繞給定ID的5個條目。

set @row=0; 
set @rk2=-1; 
set @id=2; 

select b.* from (
    select a.*, @row:[email protected]+1 as rank, if([email protected], @rk2:[email protected], -1) as rank2 
    from (
    select a.ownerid,a.quantity 
    from tbl_items a 
    where a.classid=514) a 
    order by quantity desc) b 
where b.rank > @rk2 - 3 
limit 5; 

雖然你會得到一個額外的列rank2:你可能想,而不是列b.*的顯式列表過濾出來。也許有可能是一個having子句,而不是一個額外的嵌套。

2)3排名靠前的條目+ 1個特定ID

select b.* from (
    select a.*, @row:[email protected]+1 as rank 
    from (
    select a.ownerid,a.quantity 
    from tbl_items a 
    where a.classid=514) a 
    order by quantity desc) b 
where b.rank < 4 or [email protected] 
+0

喜的男人,看起來不錯。然而,它給了我在「where子句」中的「未知列的排名」,對於這兩個查詢+在第二個查詢之前還有一個額外的逗號... –

+0

現在應該會更好。請嘗試一下,告訴我是否有問題。 – didierc

+1

第一次查詢導致同樣的錯誤,而第二次導致:「正確的語法使用附近'有(1,2,3)或[email protected]'在第1行」 –

相關問題