0
因此,我正在嘗試編寫一個MySQL查詢,以用三個單獨的查詢替換目前正在使用PHP進行的操作。我有一個只有兩個值的類別表:一個ID和一個名稱。還有另外兩個表,每個表都有一個引用第一個表中ID的外鍵。我需要從Categories表中獲取所有值的列表,以及每個其他兩個表中每個值的引用次數。我可以準確地從各個第二表的使用每個單獨的查詢得到計數:MySQL多個左連接導致不正確的計數值
SELECT nga_calevir_event_categories.*, COUNT(nga_calevir_events.event_id) AS event_total
FROM nga_calevir_event_categories
LEFT JOIN (nga_calevir_events)
ON nga_calevir_event_categories.id = nga_calevir_events.event_category
GROUP BY nga_calevir_event_categories.id;
和
SELECT nga_calevir_event_categories.*, COUNT(nga_usermeta.user_id) AS member_total
FROM nga_calevir_event_categories
LEFT JOIN (nga_usermeta)
ON (nga_usermeta.meta_value = nga_calevir_event_categories.id
AND nga_usermeta.meta_key = 'category_id')
GROUP BY nga_calevir_event_categories.id;
然而,當我嘗試這些查詢它開始給兩個不正確的結果結合起來計數。這是聯合查詢:
SELECT nga_calevir_event_categories.*,
COUNT(nga_calevir_events.event_id) AS event_total,
COUNT(nga_usermeta.user_id) AS member_total
FROM nga_calevir_event_categories
LEFT JOIN (nga_calevir_events)
ON nga_calevir_event_categories.id = nga_calevir_events.event_category
LEFT JOIN (nga_usermeta)
ON (nga_usermeta.meta_value = nga_calevir_event_categories.id
AND nga_usermeta.meta_key = 'category_id')
GROUP BY nga_calevir_event_categories.id;
它似乎是第一行的計數加倍。我一直在試驗這個幾個小時,現在我無法弄清楚。有任何想法嗎?如果您需要更多信息來幫助我,請告訴我。