猿问

MySQL JOIN 2 个表并分别获得两个表的总和

我有2张桌子。我需要从两个表中获取收入 - 具有相同日期和相同 user_id 的总收入(输出在图表中 - 每个用户的仪表板)。


我创建了一个运行良好的 SQL 查询,但是从第二个表中我从所有用户那里获得收入,我只需要分别显示每个用户的收入,并且表中是否存在带有日期的 user_id。我想提一下,每个用户在 2 个表中都没有行,只有使用此服务的用户。见下文:


表:user_revenue


USER_ID                CDATE             REVENUE

1                      2019-03-15        15

2                      2019-03-15        18

5                      2019-03-15        29

9                      2019-03-15        11

表:user_revenue_publisher


USER_ID                CDATE             REVENUE

1                      2019-03-15        15

1                      2019-03-15        50

9                      2019-03-15        21

9                      2019-03-15        18

我的 SQL 查询:


SELECT  a.user_id,

        a.cdate,

        a.revenue,

        SUM(b.revenue) as total_revenue

FROM    user_revenue a

           INNER JOIN user_revenue_publisher b

                ON a.cdate = b.cdate

WHERE   a.user_id=$id AND a.cdate >= DATE(NOW() - INTERVAL 30 DAY) group by cdate asc


($id = is ID user after login)


我需要将这些查询合并为一个:


$result = $pdo->query("select * from user_revenue where user_id=$id AND `cdate` >= DATE(NOW() - INTERVAL 30 DAY)"); 

$result2 = $pdo->query("select * from user_revenue_publisher where user_id=$id AND `cdate` >= DATE(NOW() - INTERVAL 30 DAY)"); 

我错误的 SQL:


USER_ID                CDATE             REVENUE

1                      2019-03-15        80 (correct)

USER_ID                CDATE             REVENUE

2                      2019-03-15        104 (BAD value, I need sum = 18)

我需要结果:


USER_ID                CDATE             REVENUE

1                      2019-03-15        80

USER_ID                CDATE             REVENUE

2                      2019-03-15        18

对于新用户 eg.USER_ID = 24 这是新注册的应该是


USER_ID                CDATE             REVENUE

24                     2019-03-15        0

我很高兴得到任何帮助。


繁华开满天机
浏览 397回答 2
2回答

红糖糍粑

如果您想要没有收入的用户,那么您需要一个外连接(或相关子查询)。所以,我建议:select ur.user_id, ur.cdate, ur.revenue,       ur.revenue + coalesce(sum(urp.revenue), 0) as total_revenuefrom user_revenue ur left join     user_revenue_publisher urp     on urp.cdate = ur.cdate and        urp.user_id = ur.user_idwhere ur.user_id = ? and      ur.cdate >= curdate() - interval 30 day group by ur.user_id, ur.cdate, ur.revenue;笔记:这= $id表明您正在使用文字值修改查询字符串。的?手段-使用的参数。使用有意义的表别名,这样查询更容易遵循。您需要left join将所有行保留在第一个表中,即使第二个表中没有行。因此,您需要处理NULL可能产生的值。

饮歌长啸

有几个问题: GROUP BY 需要所有不是聚合函数的列(如SUM(). 此外,您REVENUE在查询中显示两列,但在示例中只显示一列,因此很难判断哪一列是问题(虽然我认为它是 sum())。我认为这应该给你你想要的:   SELECT  a.user_id,        a.cdate,        a.revenue,        SUM(b.revenue) AS total_revenue           FROM    user_revenue a           INNER JOIN user_revenue_publisher b                 ON a.cdate = b.cdate        WHERE a.user_id= $id  group by a.User_ID,a.revenue, a.cdate
随时随地看视频慕课网APP
我要回答