多次加入两个表

时间:2011-08-09 11:41:20

标签: mysql join

我需要来自两个表的结果,其中一个是父表,另一个是子表以及父表用于子级子条目。

如果我执行sql查询,如:

   SELECT cc.collection_id, cc.title, cc.type, cc.alias as forum_alias,
           SUBSTRING(cc.description,1,200) as short_desc, 
           COUNT(b1.boardmessage_id) as total_threads,
           COUNT(b2.boardmessage_id) as total_replies 

   FROM contentcollections cc 
        JOIN boardmessages b1 ON b1.parent_id = cc.collection_id  
        JOIN boardmessages b2 ON b2.collection_id = cc.collection_id 

   WHERE cc.type=1 
         AND cc.is_active=1 
         AND b1.parent_type='collection' 
         AND b1.is_active=1 
         AND b2.parent_type IN('message','reply','reply_on_reply') 
   GROUP BY cc.collection_id 
   ORDER BY cc.created DESC;

它给了我错误的输出,总线程数相同,总回复数相同。如果我这样做了什么

SELECT cc.collection_id, cc.title,cc.type, cc.alias as forum_alias,
       SUBSTRING(cc.description,1,200) as short_desc,
       (SELECT COUNT(boardmessage_id) 
        FROM boardmessages 
        WHERE parent_type='collection' 
              AND collection_id=cc.collection_id 
              AND is_active=1) as total_threads,
       (SELECT count(boardmessage_id) 
        FROM boardmessages
        WHERE parent_type IN('message','reply','reply_on_reply') 
              AND collection_id=cc.collection_id AND is_active=1) as total_replies 
FROM contentcollections cc
WHERE cc.type=? AND cc.is_active=? 
ORDER BY cc.created DESC

它给了我正确答案。

我怀疑我在第二个选项中使用子查询,因此可能会降低页面呈现的性能。

请建议我同样的。非常感谢任何帮助或建议。

由于

1 个答案:

答案 0 :(得分:1)

替换:

COUNT(b1.boardmessage_id) as total_threads,
COUNT(b2.boardmessage_id) as total_replies 

使用:

COUNT(DISTINCT b1.boardmessage_id) as total_threads,
COUNT(DISTINCT b2.boardmessage_id) as total_replies 

如果您只希望每行计数一次,而不是默认值,则计算所有组合。 如果b1中有3行,b2中有5行,则总共有15行,并且两个计数都返回15行,而distinct标志则得到答案3和5,因为它有3个不同的值b1和b2中的5个不同值。