我有 3 个 MySQL 查询,就像这样;
$q1 = "SELECT id,date,quantity1,quantity2,total FROM test WHERE type='pencil' AND MONTH(date)='$month' AND YEAR(date)='$year' ORDER BY id";
$r1 = mysql_query($q1);
$q2 = "SELECT SUM(total) AS stotal FROM test WHERE type='pencil' AND MONTH(date)='$month' AND YEAR(date)='$year' GROUP BY id ORDER BY id";
$r2 = mysql_query($q2);
$q2 = "SELECT AVG(ROUND(total)) AS atotal FROM test WHERE type='pencil' AND MONTH(date)='$month' AND YEAR(date)='$year' GROUP BY id ORDER BY id";
$r2 = mysql_query($q2);
我如何结合这 3 个查询?所以我可以在一个while循环中使用它。我已经在while循环中尝试了multiple语句,就像这样;
$lastr = '';
while ((list($id, $date, $q1, $q2, $total) = mysql_fetch_row($r1)) && ($row = mysql_fetch_array($r2)) && ($row = mysql_fetch_array($r3))) {
if ($lastr != $id ) {
if ($lastr != '') {
// output row
echo "<tr><th>$lastr</th><th>$stotal</th><th>$atotal</th><td>";
echo join('</td><td>', $rowdata) . "</td></tr>\n";
}
$rowdata = $empty;
$lastr = $id;
}
$rowdata[$rdate] = $q1 .= '</td><td>' . $q2 .= '</td><td>' . $total;
}
当我只使用第一个查询时,所有内容都打印在我的表上,但是当我添加 2 个额外的“和”语句时,输出受到限制。顺便说一句,我试图生成一个动态列和行,只有当我在 while 循环中使用第一个查询时才有效。谢谢
非常感谢:raheel shan
我的问题的答案是:
SELECT
t.id,
t.date,
t.quantity1,
t.quantity2,
t.total,
lt.stotal,
lt.atotal
FROM test as t
left join (select
id,
SUM(total) AS stotal,
AVG(ROUND(total)) AS atotal
from test
WHERE type = 'pencil'
AND MONTH(date) = '$month'
AND YEAR(date) = '$year'
GROUP BY id) as lt
on lt.id = t.id
WHERE type = 'pencil'
AND MONTH(date) = '$month'
AND YEAR(date) = '$year'
ORDER BY id