MYSQL加入没有带来正确的结果

时间:2018-02-27 21:22:51

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

我创建了以下查询,其中包含2个连接,并且工作正常:

<div>
  <script type="application/ld+json">
    [{&quot;@context&quot;: &quot;http://schema.org&quot;}]
  </script>
</div>

输出结果如下:

SELECT a.name, b.tid
FROM table1 a INNER JOIN
     table2 b
     ON a.id = b.id
INNER JOIN (
  SELECT b2.id, b2.status,  MAX(b2.created_time) as max_time
  FROM oac.qualys_scan b2
  GROUP BY b2.id  ,  b2.qualys_type
  ) t on t.id = a.id  
      AND  t.status=b.status
      AND t.max_time = b.created_time
WHERE b.status = 'FAIL';

我有另一个表table3,其中包含以下值

id      tid     name
17695   19512   abc.com
17781   19628   abc1.com
17805   19732   abc2.com
17806   19703   abc3.com
17807   19704   abc4.com

我想在id tid name details 842 19512 abc.com Details Description 1 843 19628 abc1.com Details Description 2 上使用table3加入上述查询,以便获得以下输出

tid

我正在使用以下查询,但它只返回一行不正确

id      tid     name          details      
17695   19512   abc.com       Details Description 1
17781   19628   abc1.com      Details Description 1

1 个答案:

答案 0 :(得分:0)

使您的查询成为子查询并将其加入表格

    WITH BASELINE AS
    (
    SELECT a.name AS name, b.tid AS tid
    FROM table1 a INNER JOIN
         table2 b
         ON a.id = b.id
    INNER JOIN (
      SELECT b2.id, b2.status,  MAX(b2.created_time) as max_time
      FROM oac.qualys_scan b2
      GROUP BY b2.id  ,  b2.qualys_type
      ) t on t.id = a.id  
          AND  t.status=b.status
          AND t.max_time = b.created_time
    WHERE b.status = 'FAIL';
    )
    -------------------------------------------------------------------
    SELECT
     base.tid
     , base.name
     , t3.details

    FROM
     BASELINE base
    LEFT JOIN 
     Table3 t3
    ON base.tid = t3.tid

这不是最好的解决方案,但它始终适合我