2012-10-27 74 views
1

我有一个涉及很多表和左连接的MySQL情况,并且我有通过它的问题!解决多表的左连接问题

我会尽量简化它一步一步。

我想要做的主要任务是连接两个表。第一个表格包含项目,第二个表格包含对项目执行的操作。我需要的项目表中的每一行输出(即使没有行动是对它们执行),所以左连接似乎是解决方案:

select item.ID, count(action.ID) as cnt 
from item 
left join action on action.itemID=item.ID 
group by ID 

下一步是,我确实需要来算只有某些类型项目。由于我不需要其他类型,因此我使用where子句将其过滤掉。

select item.ID, count(action.ID) as cnt 
from item 
left join action on action.itemID=item.ID 
where item.type=3 
group by ID 

现在事情变得有点复杂了。我还需要使用另一个表(info)过滤掉一些项目。在那里,我不知道该怎么做。但是一个简单的连接和where子句做到了。

select item.ID, count(action.ID) as cnt 
from (item, info) 
left join action on action.itemID=item.ID 
where item.type=3 and info.itemID=itemID and info.fr is not null 
group by ID 

到目前为止好。我的查询工作正常,性能如预期。现在,我需要做的最后一件事就是根据另一个表(子操作)筛选出一些操作(不计算它们)。这是事情变得非常缓慢,让我困惑的地方。我试过这个:

select item.ID, count(action.ID) as cnt 
from (item, info) 
left join (
      action join subaction on subaction.actionID=action.ID and subaction.type=6 
     ) on action.itemID=item.ID 
where item.type=3 and info.itemID=itemID and info.fr is not null 
group by ID 

在这一点上,查询突然减慢了超过1000倍。我显然做错了!

我尝试了一个简单的查询,几乎可以满足我的需求。唯一的问题是不包括必须匹配操作的项目。但我也需要它们。

select item.ID, count(action.ID) as cnt 
from item, info, action, subaction 
where item.type=3 and info.itemID=itemID and info.fr is not null and 
     action.itemID=item.ID subaction.actionID=action.ID and subaction.type=6 
group by ID 

有人建议如何解决这样的问题?有没有一个标准的方法来做到这一点?非常感谢 !

编辑

其实,我提交的最后一个查询几乎是我所需要的:它不包括子查询,确实是高性能,让我索引的最佳利用,易于阅读,等

select item.ID, count(action.ID) as cnt 
from item, info, action, subaction 
where item.type=3 and info.itemID=itemID and info.fr is not null and 
     action.itemID=item.ID subaction.actionID=action.ID and subaction.type=6 
group by ID 

不工作是不包括item.ID当计(action.ID)为0

所以我想我的问题还真是应该怎么稍微修改上述唯一的小东西阙ry,这样它在count(action.ID)为0时也返回item.IDs。从我看到的情况来看,这不应该改变性能和索引使用。只需将这些额外的item.ID与0作为计数。

+1

您是否尝试过'EXPLAIN'ing查询? –

回答

1

尝试如下连接(首次尝试加入之前,应用过滤器条件):

 SELECT item.ID, count(action.ID) as cnt 
     FROM item JOIN info 
      ON (item.type=3 AND info.fr is not null AND info.itemID=item.itemID) 
      LEFT JOIN action 
      ON (action.itemID=item.ID) 
      JOIN subaction 
      ON (subaction.actionID=action.ID and subaction.type=6) 
     GROUP by item.ID; 

编辑:

 SELECT item.ID, count(action.ID) as cnt 
     FROM item JOIN info 
      ON (item.type=3 AND info.fr is not null AND info.itemID=item.itemID) 
      LEFT JOIN 
      (select a.* FROM action 
       JOIN subaction 
       ON (subaction.actionID=action.ID and subaction.type=6)) AS act 
      ON (act.itemID=item.ID) 
     GROUP by item.ID; 
+0

问题在于最后的JOIN会让我松散的项目不存在。换句话说,最后一个JOIN取消了LEFT JOIN的效果。 –

+0

如果我最后加入左连接,我会得到正确的结果,但性能会急剧下降。 –

+0

@GillesjrBisson在答案中增加了另一个查询。你可以请尝试让我知道,如果这有帮助吗? –