我有四张桌子 用户,工资,奖金,罚款 我想选择薪水,包括一些用户的所有奖金和罚款 我在每个表中都有user_id(工资,奖金,罚款) 我怎样才能做到这一点 可以有两个或更多的奖金和罚金 我试着做
BEGIN
SELECT SUM(salary.salary) + SUM(bonus.bonus) - SUM(penalty.penalty) FROM users
INNER JOIN salary on salary.user_id = users.id
INNER JOIN bonus on bonus.user_id = users.id
INNER JOIN penalty on penalty.user_id = users.id;
END
但是每次奖金和罚款都有多个结果 我想只有一个号码 谢谢你的帮助
答案 0 :(得分:1)
假设给定用户可以在每个salary
,bonus
和penalty
表中有多个记录,这里的一个安全方法是在单独的子查询中汇总金额,然后将结果连接在一起:
SELECT
u.id,
COALESCE(s.salary, 0) + COALESCE(b.bonus, 0) - COALESCE(p.penalty, 0) AS amount
FROM users u
LEFT JOIN
(
SELECT user_id, SUM(salary) AS salary
FROM salary
GROUP BY user_id
) s
ON u.id = s.user_id
LEFT JOIN
(
SELECT user_id, SUM(bonus) AS bonus
FROM bonus
GROUP BY user_id
) b
ON u.id = b.user_id
LEFT JOIN
(
SELECT user_id, SUM(penalty) AS penalty
FROM penalty
GROUP BY user_id
) p
ON u.id = p.user_id
您可以在上面添加WHERE
子句以限制一个或多个用户,例如
WHERE u.id = some_value