在php中加入2表和sum

时间:2015-04-24 09:23:22

标签: php mysqli

我正在尝试从PHP中使用MYSQL加入2个表。但是当我得到结果时,它显示出多重结果。我不知道我的剧本中有什么问题。请帮忙。我的脚本如下表所示:

  table1: sale
  id    party    amount
  1     Topu     1000
  2     Rashed   2000
  3     Topu     5000 
  4     Topu     7000
  5     Rashed   5000

  table2: party_ledger

  id    party    payment_amount
  1     Topu          2000
  2     Rashed        7000
  3     Topu          4000 
  4     Topu          5000
  5     Rashed        4000

  <?php
  $sql= "SELECT sale.party, party_ledger.party, SUM(sale.amount) AS amount,
  SUM(party_ledger.payment_amount) AS pamount FROM sale
  INNER JOIN party_ledger ON sale.party=party_ledger.party
  GROUP BY sale.party,party_ledger.party";

  $result = $cn->query($sql);

  while($row = $result->fetch_assoc()) { ?>

  <tr style="font-size: 10px">

  <td><?php echo $row['amount']; ?></td>

  <td><?php echo $row['pamount']; ?></td>

  </tr>

  <?php   }
  $cn->close(); ?>

不幸的是我得错了结果。请帮忙。

2 个答案:

答案 0 :(得分:1)

$sql= "SELECT sale.party, party_ledger.party, SUM(sale.amount) AS amount,
      SUM(party_ledger.payment_amount) AS pamount FROM (select party,sum(amount) as amount from sale group by party) sale
      INNER JOIN (select party,sum(payment_amount) as payment_amount from party_ledger group by party) party_ledger ON sale.party=party_ledger.party GROUP BY sale.party,party_ledger.party";

您可以尝试以上查询

答案 1 :(得分:-1)

我不确定它是否会起作用...但我想它会给你一个想法..你需要先在第一张桌子上查询你想要的结果,然后在第二张桌子上做同样的事情。可以加入他们两个。

SELECT SUM(tbl_sale.total_amt) as sale_total, SUM(tbl_pt_ledger.ledger_total_amt) as ledger_total FROM (SELECT party, SUM(amount) as total_amt FROM sale GROUP BY party) tbl_sale INNER JOIN (SELECT party, SUM(payment_amount) as ledger_total_amt FROM party_ledger GROUP BY party) tbl_pt_ledger ON tbl_sale.party = tbl_pt_ledger.party