我一直在遇到这个问题最困难的时候。我有 2 个表,它们的总列数要一起求和。它们都有相同的列,我使用两个表,一个是脚本生成的数据表,另一个是用户输入的数据,我们需要将它们分开。除了现在我们需要将它们相加(总计)。
表格1
+-----------+-----+--------+------+
| date |t_id | t_port | total|
+-----------+-----+--------+------+
|2012-04-01 | 1271| 101 | 80.00|
+-----------+-----+--------+------+
表 2
+----------+------+--------+-------+
| date | t_id | t_port | total |
+----------+------+--------+-------+
|2012-04-20| 1271 | 101 | 120.00|
+----------+------+--------+-------+
总额应为 200.00 美元
这是我的查询
"SELECT SUM(cntTotal) as total FROM CBS_WO WHERE (date BETWEEN '$monthSecond' AND '$monthEnd') AND t_port = '$t_port' AND t_id = '$t_id' UNION SELECT SUM(cntTotal) as total FROM CNT_MODS WHERE (date BETWEEN '$monthSecond' AND '$monthEnd') AND t_port = '$t_port' AND t_id = '$t_id'"
当我得到 2 行时,此查询似乎在 phpMyAdmin 中有效。(每个表 1 个),从逻辑上讲,我在 PHP 中使用了 WHILE 循环将两行添加在一起。手动回显每一行后,我发现我的第二行没有出现在循环中,但它出现在查询中?
无法弄清楚为什么会发生这种情况,我确信这很愚蠢,但我已经在这个代码中工作了 16 多个小时,需要一双新的眼睛。
PHP代码
function periodTotal()
{
include('/sql.login.php');
$t_id = "1271";
$t_port = "101";
$date = date("Y-m-d");
# FIND MONTH (DATE)
$monthStart = date("Y-m-d", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
$monthFirst = date("Y-m-d", strtotime('-1 second',strtotime('+15 days',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
$monthSecond = date("Y-m-d", strtotime('-1 second',strtotime('+16 days',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
$monthEnd = date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
if ($date = $monthFirst)
{
$sql = $dbh->prepare("SELECT SUM(cntTotal) as total FROM CBS_WO WHERE (date BETWEEN '$monthStart' AND '$monthFirst') AND t_port = '$t_port' AND t_id = '$t_id' UNION SELECT SUM(cntTotal) as total FROM CNT_MODS WHERE (date BETWEEN '$monthStart' AND '$monthFirst') AND t_port = '$t_port' AND t_id = '$t_id'");
$sql->execute();
}
else
{
$sql = $dbh->prepare("SELECT SUM(cntTotal) as total FROM CBS_WO WHERE (date BETWEEN '$monthSecond' AND '$monthEnd') AND t_port = '$t_port' AND t_id = '$t_id' UNION SELECT SUM(cntTotal) as total FROM CNT_MODS WHERE (date BETWEEN '$monthSecond' AND '$monthEnd') AND t_port = '$t_port' AND t_id = '$t_id'");
$sql->execute();
}
while($row = $sql->fetch(PDO::FETCH_ASSOC))
{
$total += $row['total'];
}
return $total;
}