简体   繁体   English

MySQL联接3表查询

[英]Mysql join 3 tables query

I have 3 tables like following: 我有3张桌子,如下所示:

branch
id   name
---------
1    abc
2    xyz

users
id branch_id name
-----------------
1  1         aa
2  1         bb
3  2         cc
4  1         dd
5  2         ee

sales

id user_id product  price
1   1      xxxx     10
2   1      yyyy     20
3   2      zzzz     18
4   3      aaaa     12
5   2      bbbb     10
6   4      cccc     20

Now I want to get the total selling amount branch wise like: 现在我想明智地获得总销售金额,例如:

branch_id total_price
---------------------
1         78     
2         12

For that i write a sql query like: 为此,我写一个SQL查询,像:

SELECT SUM(s.price) , b.id
FROM sales s
JOIN branch b
GROUP BY id
HAVING s.user_id
IN (
SELECT id
FROM users
WHERE branch_id = b.id
)

But this does not provide the answer that I want. 但这没有提供我想要的答案。 Please help me. 请帮我。

You could use something like this: 您可以使用如下形式:

SELECT u.branch_id, SUM(s.price) AS total_price
FROM sales AS s INNER JOIN users u ON s.user_id = user.id
GROUP BY u.branch_id
ORDER BY u.branch_id

I think this should do the trick: 我认为这应该可以解决问题:

SELECT  branch.id AS branch_id, SUM(s.price) AS total_price
FROM branch
JOIN users  ON branch.id = users.branch_id
JOIN sales ON users.id = sales.user_id
GROUP BY branch.id;

Also you could use INNER JOIN instead of JOIN (Both are doing the same thing). 您也可以使用INNER JOIN代替JOIN (两者都在做相同的事情)。 With INNER JOIN it is possibly easier to read, especially your query contains other types of JOIN 's like LEFT JOIN or RIGHT JOIN 使用INNER JOIN可能更容易阅读,特别是您的查询包含其他类型的JOIN ,例如LEFT JOINRIGHT JOIN

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM