我有8个不同产品类别的数据库供下载。
pic, app, ebo, tem, des, cod, mus, cat
我想计算客户下载的总产品数和每个产品类别的总下载量。 类别产品的每日下载限额为3。 用户登录时应查看剩余的下载量。 这是工作代码
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." products.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'pic'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ." downloaded pictures";
$leftovers = 3 - $row['sum'];
echo " $leftovers pictures remain for download";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'app'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ."downloaded applications";
$leftovers = 3 - $row['sum'];
echo " $leftovers applications remain for download.";
echo "<br />";
}
$query = "SELECT CO.... This procedure repeat eight times for different product category.
结果
You have downloaded 12 products.
3 downloaded pictures 0 pictures remain for download.
1 downloaded applications 2 applications remain for download.
3 downl.......
答案 0 :(得分:1)
您可以使用GROUP BY语句对结果进行分组。
SELECT COUNT(`Product`) AS `Sum`, `Product`
FROM `service_downloads`
WHERE `client_id` = '<client_id>'
GROUP BY `Product`
然后你可以使用一个while语句遍历每个产品:
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['Sum'] ."downloaded " . $row['Product'];
$leftovers = 3 - $row['Sum'];
echo " $leftovers " . $row['Product'] . " remain for download.";
echo "<br />";
}
答案 1 :(得分:0)
您应该在一个查询中细分每个类别的下载量:
SELECT product,COUNT(*)
FROM service_downloads
WHERE client_id like '$client';
我也不认为你需要使用LIKE;你可能想用=
答案 2 :(得分:0)
您可以使用此查询获得包含其中所有总和的单个结果集。
SELECT COUNT(*) as sum, product
FROM service_downloads
WHERE client_id = '$client'
AND PRODUCT IN ('pic', 'app', 'abc', 'def', 'ghi')
GROUP BY product WITH ROLLUP
ORDER BY product NULLS FIRST
这将为每个特定产品提供一行,并为产品列中的NULL值提供汇总(汇总)行。
如果此查询需要很长时间在(client, product
上创建一个索引,那么它应该会非常快。
答案 3 :(得分:0)
如果您经常显示此数据,这听起来像是这样,那么您应该有一个表示这些SUM的单独表,并且是CLIENT_ID索引。
每次添加新条目时,都可以递增/递减该值。
例如,当您向service_downloads添加一个新行时,如果CLIENT_ID为'pic',则您还会增加此快捷方式表:
UPDATE service_counts SET pic=pic+1 WHERE client_id=1;
答案 4 :(得分:0)
$query = "SELECT COUNT(*) as sum,product FROM service_downloads where client_id like '$client' GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." ".$row['product'];
echo "<br />";
}
这应该有效