簡體   English   中英

使用group by返回帶有max()的行

[英]Using group by to return a row with max()

我正在嘗試獲取它們的item_id存在於數組(arr_items)中且具有較高num的項目。

player_id | item_id | num | unique_number
-----------------------------------------
10        |    1    |  1  |      1
10        |    1    |  11 |      2
10        |    1    |  93 |      3
10        |    2    |  24 |      4
10        |    2    |  40 |      5

預期的結果是獲得編號為93的item_id 1,編號為40的item_id 2。

以下查詢不返回任何結果。 如果刪除num中的max ,它可以工作,但不會返回num最高的item_id。 假設arr_items = [1,2]

SELECT a.player_id, a.item_id, a.num, a.unique_number
FROM my_table a
    INNER JOIN
    (
        SELECT player_id, item_id, max(num) AS max_num, unique_number
        FROM my_table
        WHERE
        player_id = 10
        AND item_id IN (arr_items)
        GROUP BY item_id
    ) b ON a.item_id = b.item_id AND
           a.player_id = b.player_id AND
           a.num = b.max_num AND
           a.unique_number = b.unique_number
;

編輯:如果我從ON子句中刪除unique_number ,但上面的查詢工作正常,但我不太明白為什么。 我還注意到,如果我有唯一的item_id,那么它將與on子句中的unique_number字段一起使用。

這意味着如果我的桌子如下所示,它將可以正常工作。 (item_id值已更改)

player_id | item_id | num | unique_number
-----------------------------------------
10        |    0    |  1  |      1
10        |    1    |  11 |      2
10        |    2    |  93 |      3
10        |    3    |  24 |      4
10        |    4    |  40 |      5

MySQL提供了一種非標准的使用分組的方法,令人遺憾的是,“分組”已經使許多人“相信”分組就像掉日志一樣簡單,但是它卻可以以某種方式正確地猜測/解釋所需邏輯的平衡。 事實是,雖然分組很容易,但是MySQL允許的怪異的非標准語法並不總是正確的(結果是“近似值”),而且並不總是能夠正確猜測。

您可以輕松地修改現有查詢以實現所需的內容,但是請注意,您確實應該始終在group by子句中指定每個非聚合列。

SELECT a.player_id, a.item_id, a.num, a.unique_number
FROM my_table a
INNER JOIN (
        SELECT player_id, item_id, max(num) max_num
        FROM my_table
        GROUP BY player_id, item_id
    ) b ON a.item_id = b.item_id 
       AND a.player_id = b.player_id 
       AND a.num = b.max_num
;

將來,當MySQL確實實現窗口功能時,您將能夠使用row_number()實現所需的功能,並且效率也會更高:

select * 
from (
     select *
         , row_number() over(partition by player_id, item_id
                             order by num DESC) as rn
     from my_table
     ) d
where rn = 1

nb:第二個查詢始終僅對每個player_id, item_id返回一行player_id, item_id但如果對每個player_id, item_id重復num = max(num),則上面的第一個查詢可能返回多個行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM