我正在处理一个包含显示carid(foreign key from tbl_vehicle) reg_num(registration number or plate number of a car, from tbl_vehicle)
和amount(from tbl_fuel)
的项目,我成功显示了carid
,reg_num
和amount
的值使用此SQL语句以HTML格式从表tbl_fuel
和tbl_vehicle
中提取数据。
$Withdraw = query("SELECT tbl_fuel.carid,tbl_vehicle.reg_num,sum(trim(replace(amount, '$', '')) + 0.0) as amount
FROM tbl_fuel
LEFT JOIN tbl_vehicle
on tbl_fuel.carid=tbl_vehicle.carid
GROUP BY carid");
但是我忘记了另一个名为tbl_maintenance的表,它具有与tbl_fuel相同的属性,分别为carid(foreign key from tbl_vehicle)
,amount
。
我需要以单个HTML格式显示tbl_fuel
和tbl_maintenance
中的此属性的值。
这是我的html表单
<div class="panel-body">
<h3 align="center">Withdrawal Per Vehicle</h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Plate Number</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php foreach($Withdraw as $w): ?>
<?= '<tr>' ?>
<?= '<td>' . $w["carid"] . '</td>' ?>
<?= '<td>' . $w["reg_num"] . '</td>' ?>
<?= '<td>' . $w["amount"] . '</td>' ?>
<?= '</tr>' ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
请注意,上述代码可以正常运行,我的问题是,应在我当前的SQL语句中添加哪一行SQL行,以包含tbl_maintenance中的属性值并将其显示在我的HTML表单中,并将tbl_maintenance和tbl_fuel的龋齿分组并求和来自tbl_maintenance和tbl_fuel的金额?
答案 0 :(得分:0)
切换一下,将tbl_vehicle设为主表,并对总和进行子查询:
SELECT v.carid,
v.reg_num,
IFNULL(f.sum_amount,0) + IFNULL(m.sum_amount,0) AS amount
FROM tbl_vehicle v
LEFT JOIN
(SELECT carid,
sum(trim(replace(amount, '$', ''))+0) sum_amount
FROM tbl_fuel
GROUP BY cardid) f ON f.carid = v.carid
LEFT JOIN
(SELECT carid,
sum(trim(replace(amount, '$', ''))+0) sum_amount
FROM tbl_maintenance
GROUP BY cardid) m ON m.carid = v.carid
WHERE f.sum_amount IS NOT NULL OR m.sum_amount IS NOT NULL
答案 1 :(得分:0)
SELECT tbl_fuel.carid,tbl_vehicle.reg_num,sum(trim(replace(tbl_fuel.amount, '$', '')) + 0.0) as FuelAmount , sum(trim(replace(tbl_maintenance.amount, '$', '')) + 0.0) as MaintenanceAmount
FROM tbl_fuel
LEFT JOIN tbl_vehicle
on tbl_fuel.carid=tbl_vehicle.carid
LEFT JOIN tbl_maintenance
on tbl_maintenance.carid=tbl_vehicle.carid
GROUP BY carid