计算三重连接中每个表的记录

时间:2017-07-20 01:41:08

标签: mysql

我有这些表格:

用户

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

我想创建一个单独的表格,告诉我每个用户他拥有多少本书,以及他拥有的总页数和电子书数量以及总页数。

报告

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 个答案:

答案 0 :(得分: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

您当前查询的问题在于,如果给定用户拥有多本图书,您可能会多次计算同一页面。像我上面那样做单独的聚合是避免这种重复计算问题的一种方法。