仅选择最新记录

时间:2019-12-10 10:08:38

标签: mysql sql

有一个MariaDB表

calldate timestamp,
channel  varchar(30) 

值是:

2019-12-01 SIP/91953838-084ec34
2019-12-02 SIP/91953838-023ec35
2019-12-03 SIP/91953839-03e4523
2019-12-04 SIP/91953839-0365hee

如何为每个频道仅选择最新记录?

所以我需要的结果是:

2019-12-02 SIP/91953838
2019-12-04 SIP/91953839

'91953838'或'91953839'实际上是通道号(大约50个唯一值),而'084ec34'只是随机分配给每个调用的系统代码,因此没有这样的两个记录:

    2019-12-01 SIP/91953838-084ec34
    2019-12-02 SIP/91953838-084ec34

表包含10+百万行,因此我需要最有效的查询。 Mysql Ver 15.1 Distrib 5.5.60-MariaDB,

1 个答案:

答案 0 :(得分:3)

使用ROW_NUMBER,我们可以尝试:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY SUBSTRING_INDEX(channel, '-', 1) ORDER BY timestamp DESC) rn
    FROM yourTable
)

SELECT timestamp, channel
FROM cte
WHERE rn = 1;

如果您的MySQL / MariaDB版本不支持ROW_NUMBER,那么我们必须做更多的工作:

SELECT t1.timestamp, t1.channel
FROM yourTable t1
INNER JOIN
(
    SELECT SUBSTRING_INDEX(channel, '-', 1) AS channel, MAX(timestamp) AS max_timestamp
    FROM yourTable
    GROUP BY SUBSTRING_INDEX(channel, '-', 1)
) t2
    ON SUBSTRING_INDEX(t1.channel, '-', 1) = t2.channel AND
       t1.timestamp = t2.max_timestamp;