MySQL Union语句和计数

时间:2019-04-11 03:37:11

标签: mysql

我正在尝试计算同一标题的出现次数。

我的代码

SELECT 

client AS Client,
datescanned as "Date Scanned",
scanner AS Scanner,
risk AS Risk, 
host AS Host, 
name AS Title, 
solution AS Solution
FROM sss1webapp_latest

WHERE risk regexp "Critical|High" 
AND client = "myself" 
group by Title;

UNION

SELECT 


client AS Client,
datescanned as "Date Scanned",
scanner AS Scanner,
AttackScore AS Risk, 
WebSite AS Host, 
AttackType AS Title, 
Recommendation AS Solution
FROM sss2webapp_latest
WHERE AttackScore regexp "5-Critical|4-High" 
AND client = "myself"

我的表格(只是一种表示,并未添加所有字段...)

client  datescanned  title  ....
myself  2019-03-11  Backported Security Patch 
myself  2019-03-11  Backported Security Patch
myself  2019-03-11  Backported Security Patch Detection (SSH)
myself  2019-03-11  Backported Security Patch Detection (SSH)
myself  2019-03-11  Backported Security Patch Detection (SSH)
myself  2019-03-11  Backported Security Patch Detection (SSH)
myself  2019-03-11  SSL Version Issues

我想要的输出

count client datescanned title
2     myself  2019-03-11    Backported Security Patch 
4     myself  2019-03-11    Backported Security Patch Detection (SSH)
1     myself  2019-03-11    SSL Version Issues

(添加计数和分组相同的标题并计算出现的次数。

在select语句之后尝试将count(0)作为tcount添加,但是出错。

欢迎反馈! 谢谢!娜塔莉(Nathalie)

2 个答案:

答案 0 :(得分:0)

 select count(*) as count, client, datescanned, title, risk AS Risk  
 from sss1webapp_latest 
 where risk regexp "Critical|High" AND client = "myself"  group by title 

 union

 select count(*) as count, client, datescanned, title, AttackScore AS Risk 
 from sss2webapp_latest 
 where AttackScore regexp "5-Critical|4-High" AND client = "myself" group by title 

您可以选择其他列,但列号应相同,union的名称也应

答案 1 :(得分:0)

我认为结合使用count(*)sum(*)可以达到预期的效果。您可能还应该将其用作UNION ALL而不是UNION,因为我们希望对重复记录进行计数。看看这个数据库小提琴:https://www.db-fiddle.com/f/uVbD2izXHGPjCkkyk1GHRn/2

您可能需要通过添加额外的列和where子句来稍微调整查询。

我从另一个答案中总结了这个想法:https://stackoverflow.com/a/32377265/9842191