SELECT A.id as ActivityId, A.description, T.id, T.title, COUNT(R.*) as reactionCount
FROM activities
LEFT JOIN activitiesReactions as R ON R.activityId = A.id
LEFT JOIN activitiesTags as T ON A.tagId = T.id
所以基本上我需要一個查詢,將得到所有的活動,並在同一時間無法獲得該活動的反應,但得到的反應,這是在所謂的activitiesReactions另一個表中找到的計數,我該如何做到這一點(請參閱上述查詢,我想到了)。MySQL的計數加入
所以查詢應該返回:
array('activityId' => 3, 'description' => 'doing work', 'reactionCount' => 2)
一個例子行:
Activities table:
id | description
3 doing work
4 checking mail
ActivitiesReactions table:
id | activityId | message
1 3 you never do anywork, so that must be bullshit.
2 3 yes I do alot of work!
所以現在它應該返回, 「2」 reactionCount當我執行查詢並做WHERE A.id = 3
SELECT A.id as ActivityId, A.description, COUNT(R.activityId) AS reactionCount
FROM activities
LEFT JOIN activitiesReactions as R
ON R.activityId = A.id
GROUP BY A.id
這確實奏效,但reactionCount返回爲* 2,例如,如果有3個反應,reactionCount = 6,2個反應的reactionCount = 4等。
您的示例沒有任何意義......你怎麼來了'2'作爲結果?另外,你的數組與你顯示的行不匹配 – knittl
哈哈你說得對,現在已經修復了 – user1066101