1
我需要兩個表的結果,其中一個是父表,另一個是子表以及父級子表項的子表。多次連接兩個表
,如果我做的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;
它給我的錯誤出與相同數量的總線程和相同數量的總replies.How的不斷投入,如果我做這樣的事情
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
它給了我正確的答案。
我懷疑我使用子查詢在第二個選項,因此它可能在頁面渲染的性能減慢。
請建議我相同的任何幫助或建議將不勝感激。
感謝
去走遍thsi鏈接... http://stackoverflow.com/questions/6724183/getting-data-from-two-tables-in-mysql-join-wouldnt-work-here 它可能會幫助你。 –