如何加入这些表格?

时间:2018-06-08 16:04:44

标签: mysql

我在数据库中有三个表,如下所示:

users

  user_id                     name              pbal

    1                          m1               100
    2                          m2               200
    3                          m3               300
    4                          m4               400
    5                          m5               500

payouts

    id                       user_id           amount

    1                          1                100
    2                          1                200
    3                          2                300
    4                          1                400

blocked

   id                          user_id           status
 ------                        --------          ------
    1                           2                 block
    2                           3                 block

现在,我想制作一个列表,排除user_idblocked表格中的用户,并根据pbal中的users计算新的总金额以及amount中相关行的payouts

   name                 total_amount
   -----                ------------
    m1                    800
    m5                    500
    m4                    400

我已经尝试了半个小时,但都失败了。有人能帮助我吗?

2 个答案:

答案 0 :(得分:30)

以下是一个例子:

SELECT u.name, u.user_id, MAX(u.pbal) + SUM(p.amount) AS total_amount
FROM dbo.Payouts p 
INNER JOIN dbo.Users u ON u.user_id = p.user_id
LEFT OUTER JOIN dbo.Blocked b ON u.user_id = b.user_id
WHERE b.user_id IS NULL
GROUP BY u.user_id, u.name
ORDER BY MAX(u.pbal) + SUM(p.amount) DESC;

答案 1 :(得分:6)

这是一个可能的答案:

SELECT u.name, u.user_id, 
    u.pbal + (
        -- this takes amounts from the payouts table
        SELECT SUM(p.amount) 
        FROM dbo.Payouts p 
        WHERE u.user_id = p.user_id
    ) AS total
FROM dbo.Users u
WHERE NOT EXISTS (
    -- this excludes blocked users
    SELECT *
    FROM dbo.Blocked b 
    WHERE u.user_id = b.user_id
)
ORDER BY total;

在这种情况下,我更喜欢子查询,因为它们使它更明确