我正在尝试从PHP中使用MYSQL加入2个表。但是当我得到结果时,它显示出多重结果。我不知道我的剧本中有什么问题。请帮忙。我的脚本如下表所示:
Table1: purchase
id model quantity retquantity
1 D54 10 NULL
2 D54 NULL 5
3 M90 10 NULL
4 M95 10 NULL
5 M90 5
Table2: sale
id model quantity retquantity
1 D54 5 NULL
2 D54 NULL 5
3 M90 NULL 5
4 M95 6 NULL
5 M90 10 Null
我的php脚本:
<?php
$count=0;
$sql = "SELECT purchase.model,sale.model,
SUM(purchase.quantity) AS pquantity,SUM(sale.quantity) AS squantity,
SUM(purchase.retquantity) AS retpquantity,
SUM(sale.retquantity) AS sretquantity
FROM (select model,
sum(quantity) AS pquantity,sum(retquantity) AS retpquantity from
purchase group by model)purchase
INNER JOIN (select model,
sum(quantity) AS squantity,
sum(retquantity) AS retsquantity
from sale group by model)sale
ON purchase.model=sale.model
GROUP BY purchase.model,sale.model";
$result = $cn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<td><?php echo ++$count; ?></td>
<td><?php echo $row['model']; ?></td>
<td><?php echo $row['pquantity']; ?></td>
<td><?php echo $row['squantity']; ?></td>
<td><?php echo $row['retpquantity']; ?></td>
<td><?php echo $row['retsquantity']; ?></td>
<?php }} $cn->close();?>
我没有得到任何结果。请帮忙。
答案 0 :(得分:0)
尝试使用此查询可能会有所帮助
SELECT id, SUM(model) as model, SUM(quantity) as quantity, SUM(retquantity) as retquantity FROM (
SELECT * FROM purchase
UNION ALL
SELECT * FROM sale
UNION ALL
) AS somealias GROUP BY id