如何从内部联接查询之一中获取总数?
Posted
技术标签:
【中文标题】如何从内部联接查询之一中获取总数?【英文标题】:How to get total count from one of the inner join queries? 【发布时间】:2020-08-02 11:50:11 【问题描述】:我写了下面的mysql查询,Mysql版本是8.0.18-commercial
SELECT p.server, 'Type1' AS Check_Type,
GROUP_CONCAT(vmtable.res SEPARATOR ', ') AS result
FROM server p
INNER JOIN truns t ON t.oq_id = p.oq_id
AND t.id = (SELECT t2.id FROM truns t2
WHERE t2.oq_id = p.oq_id
order by t2.created_at desc limit 1 )
INNER JOIN qvuln_info vmtable ON vmtable.run_id = t.id
LEFT JOIN qvuln_info_data vmtableinfo ON vmtableinfo.qid = vmtable.qid
WHERE p.server regexp 'server1'
GROUP BY p.server
我得到的输出是:
Hostname Check_Type result
server1 Type_ABC Result 1,Result 2,Result 3,Result 4
我想在顶层添加另一列VulCount
,该值应该来自一个内部连接查询:
SELECT t2.id
FROM truns t2
WHERE t2.oq_id = p.oq_id
order by t2.created_at desc
输出应如下所示:
Hostname VulCount Check_Type result
server1 4 Type_ABC Result 1,Result 2,Result 3,Result 4
这里,4
是
SELECT count(*)
FROM truns t2
WHERE t2.oq_id = p.oq_id
order by t2.created_at desc
【问题讨论】:
【参考方案1】:@mealhour 你不能像这样包含子查询:
SELECT p.server,
der.VulCount,
'Type1' AS Check_Type,
GROUP_CONCAT(vmtable.res SEPARATOR ', ') AS result
FROM server p
INNER JOIN truns t ON t.oq_id = p.oq_id
AND t.id = (SELECT t2.id FROM truns t2
WHERE t2.oq_id = p.oq_id
order by t2.created_at desc limit 1 )
INNER JOIN qvuln_info vmtable ON vmtable.run_id = t.id
LEFT JOIN qvuln_info_data vmtableinfo ON vmtableinfo.qid = vmtable.qid
JOIN (SELECT t2.oq_id,
count(t2.*) as VulCount
FROM truns t2
GROUP BY t2.oq_id) AS der
WHERE p.server regexp 'server1'
AND der.oq_id = p.oq_id
GROUP BY p.server
【讨论】:
我收到一个错误Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) as VulCount FROM truns t2 GROUP BY t2.oq_id) AS d' at line 53 0.078 sec
@mealhour 将t2.*
更改为每行唯一的值以获取计数,最常见的是id
列。如果您有一个独特的列,例如 id
将 count(t2.*)
更改为 count(t2.id)
,那应该为您完成以上是关于如何从内部联接查询之一中获取总数?的主要内容,如果未能解决你的问题,请参考以下文章