簡體   English   中英

在 WHERE 條件下選擇 MySQL 中的最后一條記錄

[英]Select the last record in MySQL in WHERE condition

我有一張桌子,用來存放門票和雕像的關系

ticketstatus_Id ticket_Id status_Id
===================================
1                1          1
2                1          2
3                1          3
4                2          1
5                2          2   *
6                3          1
7                4          1
8                3          2   *

我想選擇最后一個 status_Id 等於 2 的行,行在表中標記。 我想我必須在ticket_Id 列上使用GROUP BY,但它返回第一個status_Id。

這個問題是ROW_NUMBER一個很好的候選:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ticket_Id ORDER BY ticketstatus_Id DESC) rn
    FROM yourTable
)

SELECT ticketstatus_Id, ticket_Id, status_Id
FROM cte
WHERE rn = 1 AND status_Id = 2;

上述邏輯查找所有最新的行的每個ticket_Id ,由作為有序ticketstatus_Id ,其status_Id值也恰好是2。

status_Id= '2'所有記錄

Select * from TABLENAME where status_Id = '2'

status_Id= '2'最后status_Id= '2'記錄

Select * from TABLENAME where status_Id = '2' order by  ticketstatus_Id  desc limit 1

SELECT * from TABLENAME where status_Id = '2' ORDER BY ticketstatus_Id DESC LIMIT 1;

你可以用group by和一個having子句來做到這一點:

select ticket_Id, max(ticketstatus_Id)
from ticketstatuses
group by ticket_id
having max(ticketstatus_Id) = max(case when status_id = 2 then ticketstatus_Id end);

知道這是否比row_number()版本具有更好的性能會很有趣。 但是,對於性能,這可能是最好的:

select ts.*
from ticketstatuses ts
where ts.ticketstatus_Id = (select max(ts2.ticketstatus_Id)
                            from ticketstatus ts2
                            where ts2.ticket_id = ts.ticket_id
                           ) and
      ts.status_id = 2;

這可以利用(ticket_id, ticketstatus_id)上的索引。

暫無
暫無

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

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