MYSQL 连接没有带来正确的结果

标签 mysql select join inner-join outer-join

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

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';

输出如下:

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

我有另一个表 table3,它具有以下值

id  tid     name                        details
842 19512   abc.com                     Details Description 1
843 19628   abc1.com                    Details Description 2

我想将上面的查询与 tid 上的 table3 连接起来,这样我会得到以下输出

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

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

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
INNER JOIN table3 T3 on b.tid = T3.tid
WHERE b.status = 'FAIL'

最佳答案

使您的查询成为子查询并将其连接到表中

    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

这不是最简洁的解决方案,但它总是适合我

关于MYSQL 连接没有带来正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018152/

相关文章:

json - jq - 选择后获取更高级别的 key

mysql - 我应该使用两个查询,还是有办法在 MySQL/PHP 中加入这个查询?

mysql - 左连接在 MySQL 中将为空

php - MySQL ORDER BY 多列 ASC 和 DESC 未按预期工作

mysql - 查询时使用 NOT IN 和 NOT EQUAL

php - SQL排序多个数据行而不合并行

mysql - 跨多个联接查找缺失行的有效方法

php - 关于构建大数据量数据库的建议

MySQL 多选,多 Where 子句

php - 将不同表中的值相加,从其他表中获取值