gpt4 book ai didi

Mysql:从多个连接表中选择特定数据

转载 作者:行者123 更新时间:2023-11-29 07:10:01 25 4
gpt4 key购买 nike

我在思考这个 select 语句时遇到了麻烦。数据来自 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 中,它与具有 vuln_id FK 的漏洞相关联。该漏洞具有严重性,并与具有 host_id FK 的主机相关联。这是我目前所拥有的:

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 个或更多漏洞的主机。我不知道该怎么做。主机表中的每个主机条目都有多个对应的漏洞条目。我想我需要在我的 where 子句中添加一些东西,但我卡住了。

提前致谢。如果需要更多信息,请告诉我。

最佳答案

尝试使用 GROUP BYHAVING:

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

关于Mysql:从多个连接表中选择特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5186683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com