Mysql查询三个表

时间:2017-09-04 15:04:04

标签: mysql sql

我试图编写一个连接三个表的查询。 正如您在下图所示,我有:

  • 用户表
  • 费用表
  • 费用类别表

我需要获得一个结果表,按类别类型分类费用(图像上的结果表)。

enter image description here

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

此查询可以正常运行,但我确定不是正确的方法。

你能帮帮我吗?

非常感谢

1 个答案:

答案 0 :(得分:2)

您想要的查询有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;