如何在单个 table 中找到不匹配的记录?

How to find unmatched records in a single table?

我正在抓取交易记录的日志文件,我将其插入到 table 中,该文件将用于多项挖掘任务。每条记录(除其他事项外)都有一个 ID 和一个事务类型,请求或响应。 request/response 对将具有相同的 ID。

我的任务之一是找到所有没有相应响应的请求。我考虑过将 table 加入自身,其中 A.ID = B.ID AND A.type = 'req' 和 B.type = 'res',但这给了我相反的东西。

由于 ID 总是会出现一次或两次,是否有查询 select ID 而在 table 中只出现一次该 ID?

这是一种非常常见的查询类型。您可以尝试使用 GROUP BY 聚合 table 中的 ID 值,然后保留只出现一次的 ID

SELECT ID
FROM yourTable
GROUP BY ID
HAVING COUNT(*) = 1

如果您还想 return 那些只出现一次的 ID 的整个记录​​,您可以试试这个:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT ID FROM yourTable GROUP BY ID HAVING COUNT(*) = 1
) t2
    ON t1.ID = t2.ID

这会给你有请求但没有响应的那些

SELECT *
FROM your_table A LEFT OUTER JOIN
your_table B ON A.ID = B.ID 
AND A.type = 'req' and B.type = 'res'
WHERE B.ID IS NULL

直接的方法是NOT IN:

select *
from mytable
where type = 'req'
and id not in (select id from mytable where type = 'res');

您可以使用 NOT EXISTS 编写大致相同的内容,但查询变得可读性稍差:

select *
from mytable req
where type = 'req'
and not exists (select * from mytable res where type = 'res' and res.id = req.id);

然后您可以使用聚合形式,例如:

select *
from mytable
where type = 'req'
and id in 
(
  select id 
  from mytable 
  group by id 
  having count(case when type = 'res' then 1 end) = 0
);