我在围绕这个选择声明缠绕我的大脑时遇到了麻烦。数据来自3个表格(为了便于阅读,我删除了所有不必要的数据):
mysql> describe vulnerability;
+---------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+----------------+
| vuln_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| severity | int(10) unsigned | NO | | NULL | |
| host_id | int(10) unsigned | NO | MUL | NULL | |
+---------------+------------------+------+-----+---------+----------------+
mysql> describe cve;
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| cve_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| cve | varchar(15) | NO | | NULL | |
| vuln_id | int(10) unsigned | NO | MUL | NULL | |
| year | int(4) unsigned | YES | | NULL | |
+---------+------------------+------+-----+---------+----------------+
mysql> describe host;
+--------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+----------------+
| host_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| ip_addr | int(10) unsigned | NO | | NULL | |
+--------------+------------------+------+-----+---------+----------------+
我想输出漏洞数量少于2009年且严重性为3的主机数量。年份包含在CVE中,与漏洞FK的漏洞相关联。该漏洞具有严重性,并与host_id FK绑定到Host。以下是我到目前为止的情况:
mysql> select count(distinct ip_addr) from host H
inner join vulnerability V on H.host_id = V.host_id
inner join CVE C on C.vuln_id = V.vuln_id
where V.severity = 3 and C.year < 2009;
+-------------------------+
| count(distinct ip_addr) |
+-------------------------+
| 5071 |
+-------------------------+
这告诉我有超过2009年的漏洞的主机总数,这是一个良好的开端。但是,我想更进一步,只包括那些有50个或更多漏洞的主机。我不知道该怎么做。 Host表中的每个主机条目都有多个相应的漏洞条目。我想我需要在where子句中添加一些内容,但是我被卡住了。
提前致谢。如果需要更多信息,请告诉我。
答案 0 :(得分:2)
尝试使用GROUP BY
和HAVING
:
SELECT ip_addr
FROM host AS H
INNER JOIN vulnerability AS V
ON H.host_id = V.host_id
INNER JOIN CVE AS C
ON C.vuln_id = V.vuln_id
WHERE V.severity = 3 AND C.year < 2009
GROUP BY ip_addr
HAVING COUNT(DISTINCT vuln_id) >= 50
要获取计数,请将上述查询包装在另一个查询中:
SELECT COUNT(*) FROM
(
SELECT ip_addr
FROM host AS H
-- etc... same query as above
) T1