如何加入3表与2表数据和

时间:2015-01-05 19:03:44

标签: php mysql

我有3张桌子。 purchase_order,goods_receive,purchase_transaction。

***我的purchase_order标识显示为order_id。  1.我需要将所有数量表格goods_receive表汇总为订单ID。  2.其次我需要总额金额来表示purchase_transaction tabel作为订单ID。

查看我的附件图片以获得更清晰的>>

enter image description here



<?php


include("db.php");



$sqlnew="SELECT purchase_order.id , purchase_order.quantity,
 purchase_order.unit_price, purchase_order.total_amount, 
 sum(goods_receive.quantity) as qua , sum(purchase_transaction.amount) as amount 
      
       
  FROM purchase_order
 JOIN goods_receive  ON purchase_order.id = goods_receive.order_id


 JOIN purchase_transaction ON purchase_order.id = goods_receive.order_id

 GROUP BY goods_receive.order_id";

$resultnew=mysql_query($sqlnew);



?>

            <table class="table table-bordered data-table" border="1">
              <thead>
                <tr>
				<th>Order ID</th>
				
           
                  <th>Quantity</th>
				   <th> Receive Quantity</th>
                  <th>Unit Price</th>
				  <th>Total Amount</th>
				   <th>Paid Amount</th>
				  
		
				
                </tr>
              </thead>
              <tbody>
			  <?php
while($rows=mysql_fetch_array($resultnew)){
?>
                <tr class="gradeX">
				 <td><a href="purchase_order_single_details.php?id=<?php echo $rows['id']; ?>"><?php echo $rows['id']; ?></td>
				
                  <td><?php echo $rows['quantity']; ?></td>
				       <td><?php echo $rows['qua']; ?></td>
                  <td><?php echo $rows['unit_price']; ?></td>
                  <td><?php echo $rows['total_amount']; ?></td>
			<td><?php echo $rows['amount']; ?></td>
			

				
				</tr>
				
				
				
				
				<?php
}
?>

				
				
             
               </tbody>
            </table>
				
          </div>
        </div>
		
		
		
		
		
      </div>
    </div>
  </div>
</div>
<!--Footer-part-->
&#13;
&#13;
&#13;

请帮帮我......

1 个答案:

答案 0 :(得分:2)

加入计算所需总数的子查询

SELECT po.order_id, po.quantity, gr.quantity AS receive_quantity, 
    po.unit_price, po.total_amount, pt.amount AS paid_amount
FROM purchase_order AS po
JOIN (SELECT order_id, SUM(quantity) AS quantity
      FROM good_receive
      GROUP BY order_id) AS gr ON gr.order_id = po.order_id
JOIN (SELECT order_id, SUM(amount) AS amount
      FROM purchase_transaction
      GROUP BY order_id) AS pt ON pt.order_id = po.order_id