[英]Query to get the sum of a condition from one table, and add it to same condition in another table
What I have is two tables; 我有两张桌子;
heli_acft
: heli_acft
:
- acft_id
acft_id
- acft_reg
acft_reg
- acft_hours
acft_hours
heli_flt
: heli_flt
:
- flt_id
flt_id
- flt_acft
flt_acft
- flt_colhr
flt_colhr
acft_id
correlates to flt_acft
. acft_id
关联到flt_acft
。
I want to get the total sum of all flt_colhr
of each flt_acft
in the table, and then add that figure to the value of acft_hours
per acft_id
. 我想获取表中每个
flt_acft
的所有flt_colhr
的总和,然后将该数字添加到每个acft_id
的acft_hours
的值中。
The result will then be displayed as a <?php echo data[???] ?>
in a table. 结果将在表中显示为
<?php echo data[???] ?>
。
Any ideas on how I could do this? 关于如何执行此操作的任何想法?
Join the tables and calculate the sum. 合并表格并计算总和。 I use a
LEFT JOIN
to get a zero result for aircraft that have no flights. 对于没有飞行的飞机,我使用
LEFT JOIN
获得零结果。
SELECT acft_id, acft_hours + IFNULL(SUM(flt_colhr), 0) AS total_colhr
FROM heli_acft
LEFT JOIN heli_flt ON acft_id = flt_acft
GROUP BY acft_id
Assuming that acft_id
is a unique idenfifier in flt_acft
table... 假设
acft_id
是flt_acft
表中的唯一标识符...
Here is one approach to returning the specified resultset, adding the total of "hours" (from heli_flt
to the "hours" from heli_acft
: 下面是一个方法来返回结果集指定,增加的总的“小时”(来自
heli_flt
从“小时” heli_acft
:
SELECT a.acft_id
, a.acft_hours
, IFNULL(f.flt_hours,0)
, a.acft_hours + IFNULL(f.flt_hours,0) AS total_hours
FROM heli_acft a
LEFT
JOIN ( SELECT SUM(h.flt_colhr) AS flt_hours
, h.flt_acft
FROM heli_flt h
GROUP BY h.flt_acft
) f
ON f.flt_acft = a.acft_id
The inline view calculates f
calculates the sum of the hours from heli_flt
for each flt_acft
. 内联视图计算
f
为每个flt_acft
从heli_flt
计算小时的总和。 A JOIN to heli_acft
to get the acft_hours
, and we simply add the values of the two columns. JOIN到
heli_acft
以获得acft_hours
,我们只需将两列的值相加即可。 We use an "outer" join so we can return rows from heli_acft
that don't have any related rows in heli_flt
, and use an IFNULL()
function to replace a NULL value with a zero. 我们使用“外部”加入,所以我们可以从返回行
heli_acft
没有任何相关行heli_flt
,并使用IFNULL()
函数来替换零NULL值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.