【问题标题】:Including another join in MYSQL table在 MYSQL 表中包含另一个连接
【发布时间】:2018-02-27 15:40:38
【问题描述】:

我创建了以下查询,其中包括 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

【问题讨论】:

  • 我看不出你的实际输出和想要的输出有什么区别
  • 更新了我的问题
  • @mealhour 只需在您的查询中添加另一个JOIN
  • 您能粘贴查询吗?

标签: mysql select join inner-join


【解决方案1】:

那么它只是 table1 a 上的另一个内部连接:

 SELECT a.id, b.tid, a.name,  table3.details
    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 on b.tid = table3.tid
    WHERE b.status = 'FAIL';

【讨论】:

  • 其实b.tid来自table2。我编写了以下查询,但它只返回一行 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'
  • 我们无法知道的数据
  • 我把INNER JOIN table3 on a.tid = table3.tid改成了INNER JOIN table3 on b.tid = table3.tid你觉得有没有更好的写法?
  • 不,这是进行 INNER JOIN 的唯一方法
猜你喜欢
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-31
  • 2022-01-07
  • 2011-06-18
  • 2014-08-24
相关资源
最近更新 更多