SQL left join two times

杀马特。学长 韩版系。学妹 提交于 2021-02-10 14:14:44

问题


The user table looks like this:

user_id name surname
1 a aa
2 b bb
3 c cc

The book's table looks like this:

user_id book_name
1 book1
1 book2
1 book3
2 book1

The expenses table looks like this:

user_id amount_spent date
1 10 2020-02-03
1 30 2020-02-02
1 10 2020-02-01
1 15 2020-01-31
1 13 2020-01-15
2 15 2020-02-01
3 20 2020-02-01

The result which I want:

CountUsers amount_spent
2 65

Explanation: I want to count how many users have book1 and how much total they spend on a date between 2020-02-01 - 2020-02-03.

Now how the query should look like?

I am using MySQL version 8.

I have tried:

SELECT 
count(*), sum(amount_spend) as total_amount_spend
FROM
(select sum(amount_spend) as amount_spend
FROM expanses 
LEFT JOIN books ON books.user_id = expanses.user_id WHERE books.book_name ='book1 GROUP BY expanses.user_id) src'

And the result is wrong because I am getting a higher amount_spend than in my table result above. I think while joining the table there are some duplicates but I do not know how to fix them.


回答1:


I want to count how many users have book1 and how much total they spend on a date between 2020-02-01 - 2020-02-03.

I am thinking:

select count(*), sum(e.amount_spent)
from user_books ub join
     expenses e
     on ub.user_id = e.user_id
where book_name = 'book1';

Note: This assumes that user_books doesn't have duplicate rows.




回答2:


FIDDLE

You miss the date part in your code.

SELECT
count(*), sum(amount_spent) as total_amount_spend
FROM
(select sum(amount_spent) as amount_spent
FROM expanses
LEFT JOIN books ON books.user_id = expanses.user_id
WHERE books.book_name ='book1' 
and expanses.date between '2020-02-01' and '2020-02-03'
GROUP BY expanses.user_id) src;

will do a job.


Please note that you don't need to have left join here (unless you're sure that it may happen that no expenses at all for given user will be), and you don't need to have grouping in subquery. So your query could look like:

select count(distinct expanses.user_id), sum(amount_spent) as amount_spent
from expanses
inner join books on books.user_id = expanses.user_id
where books.book_name ='book1'
and expanses.date between '2020-02-01' and '2020-02-03';


来源:https://stackoverflow.com/questions/66034993/sql-left-join-two-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!