简体   繁体   English

mysql查询三张表

[英]Mysql query three tables

I'm trying to write a query that join three tables. 我正在尝试编写一个连接三个表的查询。 As you can see on the image below I have: 如您在下图所见,我有:

  • users table 用户表
  • expenses table 费用表
  • expense categories table 费用类别表

I need to get a result table that groups expenses by category typology (RESULT TABLE on the image). 我需要得到一个按类别分类费用的结果表(图像上的结果表)。

在此处输入图片说明

select users.email,
(
    SELECT IFNULL(sum(expenses.amount),0)
    FROM expenses
    JOIN expense_categories as cat
    ON cat.id  = expenses.category_id
    AND cat.type = 'home'
    WHERE expenses.user_id = users.id
) as 'home expenses'
from users

This query works correctly, but I'm sure isn't the right way to do that. 该查询可以正常工作,但是我确定这不是正确的方法。

Can you help me? 你能帮助我吗?

Thank you so much 非常感谢

The query you want has join s and one aggregation: 您想要的查询具有join和一个聚合:

SELECT u.id, u.email,
       SUM(CASE WHEN ec.type = 'home' THEN e.amount ELSE 0 END) as home, 
       SUM(CASE WHEN ec.type = 'job' THEN e.amount ELSE 0 END) as job 
FROM users u LEFT JOIN
     expenses e
     ON u.id = e.user_id LEFT JOIN
     expense_categories ec
     ON ec.id  = e.category_id
GROUP BY u.id, u.email;

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

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