简体   繁体   English

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

[英]Fetching data from 3 related tables with INNER JOIN

I want to get sum of the prices and items columns which are related to 3 tables.I am trying with INNER JOIN in the following script. 我想获得与3个表相关的价格和项目列的总和。我正在尝试使用以下脚本中的INNER JOIN It only displays 1 invoice total. 它仅显示1个发票总额。 And else statement is not displaying 0 When data is 0. 否则语句不显示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";
        }

    }
}

If you have multiple SUM function, you should probably use the GROUP BY instruction. 如果您有多个SUM函数,则应该使用GROUP BY指令。 See below https://www.w3schools.com/sql/sql_groupby.asp 请参阅下面的https://www.w3schools.com/sql/sql_groupby.asp
https://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php https://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php

try this 试试这个

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM