MySQL多个子查询优化

时间:2018-10-31 03:16:53

标签: mysql

我有3张桌子
表1具有ID单元格
表2具有ID单元格
Table3具有id1单元格->对应于Table1.id
Table3具有id2单元格->对应于Table2.id

我需要一个结果,该结果计算对id1和id2对在表3中出现了多少次,对于没有出现的结果也是如此。

所以不能简单使用 从id1,id2的表3组中选择*。

我用过

SELECT *
FROM table1, table2, 
    (SELECT COUNT(*) AS count
    FROM table3
    GROUP BY id1, id2)
GROUP BY table1.id, table2.id   

但是它的糖蜜速度很慢,并且不起作用。

2 个答案:

答案 0 :(得分:1)

尝试下一个查询:

1)首先,我们交叉联接table1和table2以获取所有组合元组。

2)其次,我们将联接保留到表3中。

3)我们计算每个元组获得的行数,不计算 table3-> id1 上的空值(这假设类型为{{1}的元组}或meteor add static-html 在table3上不存在)

The following query worked for me: 

.table("task_history")
  .count(db.raw("distinct date"))
  .where('store_id', 100)
  .where('date', '>', function() {
    this.select('date')
      .from(function() {
        this.select('date')
          .table("task_history")
          .first()
          .count('* as count_all')
          .select( db.raw("count(case when finish_time is not null then 1 else null end) as count_finished"))
          .where('store_id', 100)
          .groupBy('date')
          .orderBy('count_finished', 'asc')
          .orderBy('date', 'desc')
          .as('get_max_date')
      })
  });

答案 1 :(得分:1)

我将表1和表2交叉连接,然后在表3上将其左连接,并计算一个表达式以检查组合是否存在:

SELECT     t1.id,
           t2.id,
           COUNT(CASE WHEN t3.id1 IS NOT NULL AND t3.id2 IS NOT NULL THEN 1 END)
FROM       t1
CROSS JOIN t2
LEFT JOIN  t3 ON t1.id = t3.id1 AND t2.id = t3.id2
GROUP BY   t1.id, t2.id