2015-07-02 73 views
1

我想創建一個報告,顯示回聲的類別,然後是每個類別的total sales帶查詢的MYSQL查詢建立表格 - 多個表格和總結

數據庫跨4個表拆分:

1)類別表(保持類別名稱和id)
2)產品(選擇從這裏products通過category id
3)銷售(持有sale id s有關銷售項目)
4)銷售項目(全部保留sale itemssold amounts

我需要讓我相信了category id的產品,然後通過date拿到銷售,然後從sale items通過sale id(僅日期)和product id選擇(所以他們只能通過相應的類別)。

這是我的嘗試..但沒有工作,我不知道我什至在正確的道路上,任何幫助將不勝感激:)謝謝!

//Select The Category Table 
$query="SELECT * FROM categories"; 
$result=mysql_query($query); 
$num=mysql_numrows($result); 

while($row = mysql_fetch_assoc($result)) 
{ 
    echo $row['name']." "; 

    //store category id in a string 
    $cID = $row['id'].""; 

    //get the product id's 
    $productquery = "SELECT id FROM products WHERE category_id = $cID"; 
    $productresult = mysql_query($productquery); 
    $numproducts = mysql_num_rows($productresult); 
    $productrow = mysql_fetch_assoc($productresult); 
    $productid = $productrow['id'].""; 
// echo $productid; 


    //get sale id from table to use to get sale items 
    $salesquery = "SELECT * FROM sales WHERE date BETWEEN '2015-01-01 00:00:00' AND '2015-06-01 00:00:00'"; 
    $salesresult = mysql_query($salesquery); 
    $salesnumber = mysql_num_rows($salesresult); 
    $salesrow = mysql_fetch_assoc($salesresult); 
    $salesid = $salesrow['id'].""; 
    // echo $salesid; 

    //put it all together and try to sum up the subtotal col where only the category product will be tallied 
    $saleitemsquery = "SELECT SUM(subtotal) FROM sales_items WHERE sale_id = $salesid AND product_id = $productid"; 
    $totalresult = mysql_query($saleitemsquery); 
// $totalrow = mysql_fetch_assoc($totalresult); 
echo $totalresult; 

    ?> 
    <br /> <br /> 

    <?php 
} 
?> 
+3

你需要學習如何使用[JOIN](https://en.wikipedia.org/wiki/Join_%28SQL%29)■ –

回答

0

我相信這不是100%準確的,但希望它足以讓您走上正確的軌道。

select c.name as Name, sum(i.subtotal) as Total 
from sale_items i 
     inner join sales s on s.id = i.sale_id 
     inner join products p on p.id = i.product_id 
     inner join categories c on c.id = p.category_id 
where s.date BETWEEN '2015-01-01 00:00:00' AND '2015-06-01 00:00:00' 
group by c.id 
+0

太謝謝你了! – natan

0

要做到這一點,你必須使用JOIN。但在你使用它之前,你必須確保你的表格以某種方式連接在一起。

例如(表列) - 表類:CAT_ID,.. - 表銷售:sale_id,CAT_ID,.. 在這種情況下,它會是這樣的:

SELECT * 
FROM categories as c 
JOIN sales as s 
ON c.cat_id=s.cat_id 

若要計算出現次數,請在SELECT之後使用COUNT(table.column_to_count)