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