【问题标题】: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

【问题讨论】:

    标签: mysql join select left-join inner-join


    【解决方案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 列。如果您有一个独特的列,例如 idcount(t2.*) 更改为 count(t2.id),那应该为您完成
    猜你喜欢
    • 2013-01-27
    • 1970-01-01
    • 2016-10-27
    • 2012-12-06
    • 1970-01-01
    • 2019-12-28
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多