我有两个具有不同字段的表:
SELECT url, title, description, impact, solution, severitylevel, category
FROM admin_cyber.sss3wn
WHERE severitylevel = "5"
AND client = "user1"
UNION
SELECT name, risk, host, protocol, port, pluginoutput, description, solution
FROM admin_cyber.sss1wn
WHERE risk = "Critical" AND client = "myuser1"
AND datescanned IN (SELECT max(datescanned) FROM admin_cyber.sss1wn
常见字段是:客户端,已扫描日期
我只想查询两个表并仅检索最新日期的数据。
两个表是否都需要具有确切的字段才能出现在UNION中?
问题2:如果我知道sss3wn中的“ url”字段和sss1wn中的“ host”字段具有相同的含义,我可以将它们以相同的名称分组吗?
谢谢! 娜塔莉(Nathalie)
答案 0 :(得分:1)
对于UNION,表是否具有相同的字段无关紧要,因为两个SELECT语句上所选列的数量都匹配。
因此,两个SELECT都必须选择相同数量的列,并且每个SELECT中匹配的列都应具有相同的dataType(如果可以的话,您可以CAST强制使用相同的dataType)。
示例:
SELECT
url AS Field1,
title AS Field2,
description AS Field3,
impact AS Field4,
solution AS Field5,
severitylevel AS Field6,
category AS Field7,
"-" AS Field8
FROM admin_cyber.sss3wn
WHERE severitylevel = "5"
AND client = "user1"
UNION
SELECT
name AS Field1,
risk AS Field2,
host AS Field3,
protocol AS Field4,
CAST(port AS NVarChar) AS Field5,
pluginoutput AS Field6,
description AS Field7,
solution AS Field8
FROM admin_cyber.sss1wn
WHERE risk = "Critical" AND client = "myuser1"
AND datescanned IN (SELECT max(datescanned) FROM admin_cyber.sss1wn);
我假设所有匹配的字段都具有相同的dataType(除了solution:NvarChar和port:integer用作示例,您可以如何投射某些内容)。在第8个字段中,在第一个语句上选择了一个常量,以强制在SELECT语句之间进行相同数量的选择。
执行此UNION可能没有任何意义(在我看来,匹配的字段与其含义没有任何关系),但这就是UNION的样子。
编辑: 如果实际上来自两个SELECT的数据确实不同(含义),但仍需要将它们作为单个结果集列出,则可以执行以下操作:
SELECT
"INCIDENT" AS RowType,
url AS Url_or_Name,
title AS Title_or_Risk,
description AS Desc_or_Host,
impact AS Impct_or_Prot,
solution AS Sol_or_Port,
severitylevel AS Lvl_or_Output,
category AS Cat_or_Desc,
"-" AS Field8
FROM admin_cyber.sss3wn
WHERE severitylevel = "5"
AND client = "user1"
UNION
SELECT
"CONNECTION" AS RowType,
name AS Url_or_Name,
risk AS Title_or_Risk,
host AS Desc_or_Host,
protocol AS Impct_or_Prot,
CAST(port AS NVarChar) AS Sol_or_Port,
pluginoutput AS Lvl_or_Output,
description AS Cat_or_Desc,
solution AS Field8
FROM admin_cyber.sss1wn
WHERE risk = "Critical" AND client = "myuser1"
AND datescanned IN (SELECT max(datescanned) FROM admin_cyber.sss1wn);
或者您可能会发现,最好对选定的列进行重新排序,以使其与联合的结果列上的含义更好地匹配。