使用INNER JOIN从3个相关表中获取数据

时间:2018-06-10 09:55:07

标签: php if-statement sum inner-join

我想获得与3个表相关的价格和项目列的总和。我正在尝试使用以下脚本中的INNER JOIN。它仅显示1个发票总额。否则语句不显示0当数据为0时。

function TotalRecord($total){
global $db;
$date = date("Y-m-d");
     $query = $db->prepare("SELECT sum(a.prices), sum(a.item) FROM items a INNER 
    JOIN invoice_items b ON a.item_id = b.item_id INNER JOIN invoices c ON 
    b.invoiceId = c.invoiceId  WHERE c.invoice_date = :date ");
    $query->bindParam(':date', $date);
    $query->execute();
    for($i=0; 
             $rows = $query->fetch(); 
    $i++){
         $totalPrice = $rows['sum(a.prices)'];
         $totalitems = $rows['sum(a.item)'];
         $array = array('total' => $totalPrice , 'items' => $totalitems );

        if(count($array) > 0)
        {
            echo $array[$total];
        }
        else
        {
            echo "0";
        }

    }
}

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

试试这个

 SELECT sum(a.prices), sum(a.item) FROM (items a INNER 
JOIN invoice_items b ON a.item_id = b.item_id INNER JOIN invoices c ON 
b.invoiceId = c.invoiceId )  group by  b.item_id,b.invoiceid WHERE c.invoice_date = :date