2017-07-20 74 views
0

我有這些表:盤點記錄加入

用戶

id_user | name 
1 | First 
2 | Second 

id_book | id_user | pages 
1 | 1 | 10 
2 | 1 | 5 
3 | 1 | 30 
4 | 2 | 15 
5 | 2 | 20 

電子書

id_ebook | id_user | pages 
1 | 1 | 20 
2 | 1 | 20 
3 | 2 | 10 
4 | 2 | 20 
5 | 2 | 10 

我想創建一個單個表格告訴我每個用戶有多少書h電子書的總數,頁數,電子書總數以及頁面總數。

報告

id_user | total_books | sum_pag_books | total_ebooks | sum_pag_ebooks 
1 | 3 | 45 | 2 | 40 
2 | 2 | 35 | 3 | 40 

我有這樣的代碼:

SELECT 
user.name, 
COUNT(book.id_book) AS 'total_books', 
SUM(book.pages) AS 'sum_pag_books', 
COUNT(ebook.id_ebook) AS 'total_ebooks', 
SUM(ebook.pages) AS 'sum_pag_ebooks' 
FROM user 
LEFT JOIN book ON book.id_user = user.id_user 
LEFT JOIN ebook ON ebook.id_user = user.id_user 
GROUP BY user.id_user 

但是,結果是這樣的,是不正確的,我該如何解決這個查詢? 報告

id_user | total_books | sum_pag_books | total_ebooks | sum_pag_ebooks 
1 | 6 | 90 | 6 | 120 
2 | 6 | 105 | 6 | 80 

回答

1

你可以嘗試分別聚集兩個書表,然後加入到:

SELECT 
    user.name, 
    COALESCE(book.total_books, 0)  AS total_books, 
    COALESCE(book.sum_pag_books, 0) AS sum_pag_books, 
    COALESCE(ebook.total_ebooks, 0) AS total_ebooks, 
    COALESCE(ebook.sum_pag_ebooks, 0) AS sum_pag_ebooks 
FROM user 
LEFT JOIN 
(
    SELECT id_user, COUNT(*) AS total_books, SUM(pages) AS sum_pag_books 
    FROM book 
    GROUP BY id_user 
) book 
    ON book.id_user = user.id_user 
LEFT JOIN 
(
    SELECT id_user, COUNT(*) AS total_ebooks, SUM(pages) AS sum_page_ebooks 
    FROM ebook 
    GROUP BY id_user 
) ebook 
    ON ebook.id_user = user.id_user 

與您當前查詢的問題是,你最終可能會計算同一頁面更如果給定的用戶擁有多本書,那麼這一次就是一次。按照上面的方法分開彙總是避免這種重複計算問題的一種方法。