在WHERE条件下选择MySQL中的最后一条记录
我有一张放票和雕像的桌子在WHERE条件下选择MySQL中的最后一条记录,mysql,sql,Mysql,Sql,我有一张放票和雕像的桌子 ticketstatus_Id ticket_Id status_Id =================================== 1 1 1 2 1 2 3 1 3 4 2 1 5 2 2 * 6
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的行,这些行在表中被标记。
我想我必须使用列票证Id上的GROUP BY,但它返回第一个状态Id。所有状态Id为'2'的记录
Select * from TABLENAME where status_Id = '2'
Select * from TABLENAME where status_Id = '2' order by ticketstatus_Id desc limit 1
状态为'2'的最后一条记录
Select * from TABLENAME where status_Id = '2'
Select * from TABLENAME where status_Id = '2' order by ticketstatus_Id desc limit 1
对于
行编号
,此问题是一个很好的候选问题:
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;
上述逻辑查找每个
票证Id
的所有最新行,按照票证状态Id
的顺序,其状态Id
值也恰好为2。从表名
中选择*其中状态Id
='2'顺序由票证状态Id
描述限制1 您可以使用group by
和具有
子句来执行此操作:
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\u 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\u id,ticketstatus\u id)
上的索引。您是想定位“最后一个”状态id(由某列确定),还是这里的“最后一个”表示最大的状态id?