简体   繁体   English

跨3个相关表的SQL选择命令SUM

[英]SQL select command SUM across 3 related tables

I've changed my DB structure to make it more future proof. 我更改了数据库结构,以使其更适合将来使用。 Now I'm having trouble with the new select query. 现在,我在使用新的选择查询时遇到了麻烦。

I have table called activities that has a list of activities and how many steps per minute that activity was worth. 我有一个称为活动的表,该表具有活动列表以及该活动每分钟值得多少步。 The table was structred like this: 该表的结构如下:

Activities
id     act_name     act_steps
12     Boxing       250
14     Karate       300
17     Yoga         89

I have another table called distance that is structed like this: 我有另一个表,称为距离,其结构如下:

Distance
id     dist_activity_id    dist_activity_duration    member_id
1      12                  60                        12
2      14                  90                        12
3      17                  30                        12

I have the query that would SUM and produce a total for all activities in the distance table 我有查询将求和并生成距离表中所有活动的总计

SELECT ROUND(SUM(act_steps * dist_activity_duration / 2000),2) AS total_miles
FROM distance,
     activities
WHERE activities.id = distance.dist_activity_id

This worked fine. 这很好。

To future proof it incase the number of steps for an activity changes I've setup a table called steps that is structured like this: 为了将来证明它可以防止活动的步骤数发生变化,我设置了一个名为steps的表,其结构如下:

Steps
id     activity_steps
1      6
2      250
3      300
4      89

I then updated the activities table, removing the act_steps column and replacing it with steps_id so it now looks like this: 然后,我更新了活动表,删除了act_steps列,并将其替换为steps_id,因此现在看起来像这样:

Updated activities
id     act_name     steps_id
12     Boxing       2
14     Karate       3
17     Yoga         4

I'm not sure how to create the select command to get the SUM using the new structure. 我不确定如何创建选择命令来使用新结构获取SUM。

Could someone please help me with this? 有人可以帮我吗?

Thanks 谢谢

Wayne 韦恩

Learn to use proper JOIN syntax! 学习使用正确的JOIN语法! Your query should look like: 您的查询应类似于:

SELECT ROUND(SUM(a.act_steps * d.dist_activity_duration / 2000), 2) AS total_miles
FROM distance d JOIN
     activities a 
     ON a.id = d.dist_activity_id;

If you need to lookup the steps, then add another JOIN : 如果您需要查找步骤,请添加另一个JOIN

SELECT ROUND(SUM(s.activity_steps * d.dist_activity_duration / 2000), 2) AS total_miles
FROM distance d JOIN
     activities a 
     ON a.id = d.dist_activity_id JOIN
     steps s
     ON s.id = a.steps_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM