我希望能够显示客户拥有的商品数量和总数,并为每个商品和总价格添加价格。我无法解决如何做到这一点的逻辑。到目前为止,我可以显示客户的所有项目,但有些项目会重复。
$clientid = 24;
$query = "SELECT items.itemid, prices.priceid FROM items
JOIN prices ON items.itemid = prices.itemid
WHERE items.clientid = '$clientid'";
$result = $db_connect -> query($query);
$row_cnt = $result -> num_rows;
echo $joinrow_cnt."<br/><br/><br/>";
while($assocresult = mysqli_fetch_assoc($result)){
$price = $assocresult['priceid'];
$item = $assocresult['itemid'];
$realprice = ($price/100)*80; //after 80% discount
echo "ItemId: ".$item." Price : " .$price." real price: " .$realprice."<br/>";
}
到目前为止,我得到了:
ItemId: 1 Price : 100 real price: 80
ItemId: 3 Price : 25 real price: 20
ItemId: 1 Price : 100 real price: 80
ItemId: 5 Price : 200 real price: 160
ItemId: 3 Price : 25 real price: 20
ItemId: 1 Price : 100 real price: 80
了解ItemId 1和3的重复方式。有很多这样的行,其中重复了项ID。
我希望输出如下:
ItemId: 1x3 Price: 100 real price = 80x3=240
ItemId: 3x2 Price: 25 real price = 20x2=50
ItemId: 5 Price: 200 real price: 160 //since this item is listed only once.
请帮忙。非常感谢!!
答案 0 :(得分:2)
检查解决方案如下:
$clientid = 24;
$query = "SELECT items.itemid, prices.priceid, count(items.itemid) as itemcnt FROM items
JOIN prices ON items.itemid = prices.itemid
WHERE items.clientid = '$clientid' group by items.itemid";
$result = $db_connect -> query($query);
$row_cnt = $result -> num_rows;
echo $row_cnt."<br/><br/><br/>";
while($assocresult = mysqli_fetch_assoc($result)){
$price = $assocresult['priceid'];
$item = $assocresult['itemid'];
$itemcnt = $assocresult['itemcnt'];
$realprice = ($price/100)*80; //after 80% discount
echo "ItemId: ".$item."x".$itemcnt." Price: " .$price." real price = " .$realprice."x".$itemcnt."=".($realprice*$itemcnt)."<br/>";
}
我在第10行上没有收到任何错误。您的代码中$db_connect
的价值是多少?
让我知道。谢谢!
答案 1 :(得分:1)
您可以获取所有items
和prices
数据并将其与WHERE
匹配,然后使用GROUP BY
将重复数据收集为一行。使用COUNT(..)
,您可以获得每个项目的行数。
这应该可以解决问题:
SELECT
COUNT(items.itemid) as cnt,
items.itemid,
prices.priceid
FROM items, prices
WHERE
items.itemid = prices.itemid
AND
items.clientid = '$clientid'
GROUP BY items.itemid