不同表的sum结果,不存在返回null

0ve6wy6x  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(510)

我是mysql新手,现在有一个查询有问题。我有3个表(用户、分支和销售)。我想按用户查询并返回销售组总和的结果,如果销售组不存在,则结果为空。以下是我的表格详情:
用户

user_id username
----------------
1       adam   
2       david
3       siva

分支

branch_id   user_id
-------------
001         1       
002         1       
003         1
004         2
005         3

出售

branch_id   sales
-------------
001        20       
002        30       
003        10

下面是我的疑问;

SELECT u.username, SUM(s.sales) AS total_sales
FROM USER u
INNER JOIN branch b ON u.user_id=b.user_id
INNER JOIN sales s ON s.branch_id=b.branch_id

谢谢。

zbq4xfa0

zbq4xfa01#

SELECT u.id, SUM(IFNULL(s.sales,0)) AS total_sales
FROM USER u
left JOIN branch b ON u.user_id=b.user_id
left JOIN sales s ON s.branch_id=b.branch_id
GROUP BY u.user_id;
cu6pst1q

cu6pst1q2#

SELECT u.username, SUM(s.sales) AS total_sales
FROM USER u
LEFT JOIN branch b ON u.user_id=b.user_id
LEFT JOIN sales s ON s.branch_id=b.branch_id
GROUP BY u.user_id

相关问题