我想创建一个回显类别的报告,然后创建每个类别的total sales
。
数据库分为4个表:
1)类别表(保存类别名称和ID)
2)产品(通过products
从此处选择category id
)
3)销售(保留与销售商品相关的sale id
)
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
}
?>
答案 0 :(得分:0)
要执行此操作,您必须使用JOIN
。但在你使用它之前,你必须确保你的表以某种方式连接在一起。
例如(表格列) - 表类别: cat_id ,.. - 餐桌销售:sale_id, cat_id ,.. 在这种情况下,它将是:
SELECT *
FROM categories as c
JOIN sales as s
ON c.cat_id=s.cat_id
要计算出现次数,请在COUNT(table.column_to_count)
之后使用SELECT
。
答案 1 :(得分: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