我得到這個查詢:多個LEFT JOIN - 輸出錯誤
SELECT r.name, date(r.join_date) as join_date,
(COUNT(DISTINCT a.id) + COUNT(DISTINCT n.id)) as num_likes,
COALESCE(SUM(rv.views), 0) as sum_views
FROM restaurants r
LEFT JOIN apple_likes a ON r.id = a.restaurant_id
LEFT JOIN android_likes n ON r.id = n.restaurant_id
LEFT JOIN restaurant_views rv on r.id = rv.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC
這裏是與num_like變量和LEFT JOIN的另一個查詢中刪除:
SELECT r.name, date(r.join_date) as join_date,
COALESCE(SUM(rv.views), 0) as sum_views
FROM restaurants r
LEFT JOIN restaurant_views rv on r.id = rv.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC
正如你所看到的,sum_views更改爲1793這是正確的!
這意味着,當我刪除其他LEFT JOIN的時候,sum_views顯示正確的值。
如何讓上方的查詢在sum_views上顯示正確的值?
(我可以,如果要求上傳其他表的結構的圖像!)
編輯:
我發現使用子查詢來解決這個問題
SELECT r.name, date(r.join_date) as join_date,
(COUNT(DISTINCT a.id) + COUNT(DISTINCT n.id)) as num_likes,
(SELECT COALESCE(SUM(views), 0) FROM restaurant_views WHERE restaurant_id=192) as sum_views
FROM restaurants r
LEFT JOIN apple_likes a ON r.id = a.restaurant_id
LEFT JOIN android_likes n ON r.id = n.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC
方式
如果有人知道如何解決這個問題,而不使用子查詢,我會有興趣聽到它!
如果您使用Gordon查詢中派生的表/內聯視圖'rv',我懷疑它會起作用。 – shawnt00 2015-02-24 01:25:46