我有一个名为NetLogs的MySQL表
servername , session , label , occurence
| Nost | 11973 | Unknown | 1 |
| Nost | 11976 | Scan | 74 |
| Nost | 11976 | Unknown | 35 |
| Gold | 11998 | Attack | 1 |
我需要
Nost | 11973|unknown|1|
Nost| 11976 |Scan | 74|
Gold|11998|Attack|1|
结果。
我试过了:
select t1.* from NetLogs t1 left join NetLogs t2
on t1.servername=t2.servername and t1.session=t2.session and t1.occurence < t2.occurence
where t2.occurence is null;
但我得到错误1137 - 无法重新打开表。
我也会在没有最后出现次数的情况下找到相同的结果。
所以下面的一些解决方案对我来说不起作用所以我将表重新制作为常规表而不是临时表并且它们有效,这让我觉得我可能曾经有过一个有效的查询,但是得到错误是因为我在临时桌上运行它......
这正是我想要的方式:
从NetLogs a中选择一个。*,其中a.occurence =(从NetLogs b中选择max(出现)出现,其中a.session = b.session和a.serverName = b.serverName);
答案 0 :(得分:2)
SELECT a.*
FROM NetLogs a
INNER JOIN
(
SELECT session, MAX(occurence) occurence
FROM NetLogs
GROUP BY session
) b ON a.session = b.session AND
a.occurence = b.occurence
另一种方式,
SELECT a.*
FROM NetLogs a
WHERE a.occurence =
(
SELECT MAX(occurence) occurence
FROM NetLogs b
WHERE a.session = b.session
)
答案 1 :(得分:0)
查询:
<强> SQLFIDDLEEXample 强>
SELECT a.servername,
a.session,
a.label,
a.occurence
FROM NetLogs a
LEFT JOIN NetLogs b
ON b.session = a.session
AND a.occurence < b.occurence
WHERE b.session IS NULL
结果:
| SERVERNAME | SESSION | LABEL | OCCURENCE |
|------------|---------|---------|-----------|
| Nost | 11973 | Unknown | 1 |
| Nost | 11976 | Scan | 74 |
| Gold | 11998 | Attack | 1 |