mysql查找状态为失败的服务器

gdrx4gfi  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(372)

我有一个包含以下列的sql表 id 作为 PK , ip ,
check_type check_status :

id      ip             check_type    check_status
1       10.10.10.10    check1        FAIL
2       10.10.10.10    check2        PASS
3       10.10.10.11    check1        PASS
4       10.10.10.11    check2        PASS

我只想要 ips 有哪些 Failed Check1 and Passed Check2 从table上。所以,从上面的例子中,我的输出应该是 10.10.10.10 ```
SELECT DISTINCT
(ip)
FROM table1 a
INNER JOIN table1 b
ON a.ip = b.ip
WHERE a.check_status = 'FAIL'
AND a.check_type = 'check1'
AND b.check_status = 'PASS'
AND b.check_type = 'check2';

我犯了个错误
列ip不明确
enxuqcxy

enxuqcxy1#

使用条件聚合:

SELECT ip
FROM table1
GROUP BY ip
HAVING SUM(CASE WHEN check_type = 'check1' AND check_status = 'FAIL'
                THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN check_type = 'check2' AND check_status = 'PASS'
                THEN 1 ELSE 0 END) > 0

另一种稍微优雅一点的mysql工作方式:

SELECT ip
FROM table1
WHERE (check_type, check_status) IN (('check1', 'FAIL'), ('check2', 'PASS'))
GROUP BY ip
HAVING COUNT(DISTINCT check_type, check_status) = 2;

下面是第二个查询的演示,由@mkhalid提供

piok6c0g

piok6c0g2#

SELECT DISTINCT
  (a.ip)
FROM table1 a
INNER JOIN table1 b
  ON a.ip = b.ip
WHERE a.check_status = 'FAIL'
AND a.check_type = 'check1'
AND b.check_status = 'PASS'
AND b.check_type = 'check2';

这会有用的
你正在选择的ip是在a和b,所以它是给错误,所以当你写a.ip或b.ip它将正常工作

相关问题