如果第二个表有多个出现,如何连接表并得到第一个表的总和

时间:2016-07-11 07:43:27

标签: mysql sql

我有两个表“temp_user_batches”和“user_activities”我正在尝试查找temp_user_batches表中用户的user_activities总和。

问题是user_activities的总和乘以temp_user_batches表中用户出现次数的次数。

下面是temp_user_batches表

enter image description here

这是user_activities表

enter image description here

它应该给出time_spent列的总和649 + 364 = 1013,而是给它2016

我的查询是:

SELECT temp_user_batches.user_id as user_id, 
       temp_user_batches.activity_goal as goal,
       DATE_SUB(CURDATE(), INTERVAL 7 day) as min_activity_date, 
       CURDATE() as max_activity_date,
       (sum(user_activities.time_spent)/60) as total_time_spent
FROM temp_user_batches
INNER JOIN user_activities
   ON temp_user_batches.user_id = user_activities.user_id
WHERE activity_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 day) AND CURDATE()
group by user_id, goal, max_activity_date, min_activity_date

2 个答案:

答案 0 :(得分:1)

您可以使用包含表DISTINCTuser_id, activity_goal temp_user_batchesSELECT t1.user_id as user_id, t2.activity_goal as goal, DATE_SUB(CURDATE(), INTERVAL 7 day) as min_activity_date, CURDATE() as max_activity_date, (sum(t2.time_spent)/60) as total_time_spent FROM ( SELECT DISTINCT user_id, activity_goal FROM temp_user_batches) AS t1 INNER JOIN user_activities AS t2 ON t1.user_id = t2.user_id WHERE activity_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 day) AND CURDATE() group by user_id, goal, max_activity_date, min_activity_date 的派生表:

PNG

答案 1 :(得分:0)

根据我的理解,在GROUP_BY加入temp_user_batches之前,您应该user_id last_activity user_activitiesuser_activities。这是因为现在你按照你想要的方式加入SELECT temp_user_batches.user_id AS user_id, temp_user_batches.activity_goal AS goal, DATE_SUB(CURDATE(), INTERVAL 7 DAY) AS min_activity_date, CURDATE() AS max_activity_date, (SUM(user_activities.time_spent) / 60) AS total_time_spent FROM (SELECT * FROM temp_user_batches GROUP BY user_id , last_activity) INNER JOIN user_activities ON temp_user_batches.user_id = user_activities.user_id WHERE activity_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() GROUP BY user_id , goal , max_activity_date , min_activity_date 2行而不是1行(根据我的理解)。

类似的东西:

$result = mysqli_query($conn, "SELECT SUM(angsuran) as sumtotal FROM `laporan` WHERE id_mustahik=".$detail_campaigner->id_mustahik."");
$row = mysqli_fetch_assoc($result);
echo $row['sumtotal']; //outputs 30000