我想創建一個報告,顯示回聲的類別,然後是每個類別的total sales
。帶查詢的MYSQL查詢建立表格 - 多個表格和總結
數據庫跨4個表拆分:
1)類別表(保持類別名稱和id)
2)產品(選擇從這裏products
通過category id
)
3)銷售(持有sale id
s有關銷售項目)
4)銷售項目(全部保留sale items
和sold 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
}
?>
你需要學習如何使用[JOIN](https://en.wikipedia.org/wiki/Join_%28SQL%29)■ –