我需要一些帮助。 我即将创建一个小型电子商店,我想为每个用户添加追踪历史。
我有这个,但它不能像我想的那样工作。
$sql="SELECT * FROM transactions INNER JOIN cds ON transactions.cdCode=cds.code WHERE usrId='$userId' ORDER BY transactionId";
$result=mysqli_query($conn,$sql);
if (mysqli_num_rows($result)==0)
echo "No purchases";
echo "<table>";
while($row=mysqli_fetch_array($result))
{
echo "<tr><td>".$row['transactionId']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['cdQuantity']."</td>";
echo "<td>".$row['price']."</td>";
echo "<td>".$row['tDate']."</td>";
echo "<td>".$row['status']."</td></tr>";
}
echo "</table>";
sql文件:
CREATE TABLE transactions (
transactionId varchar(255) NOT NULL,
usrId INT NOT NULL,
cdCode varchar(35),
cdQuantity int,
tDate text,
status text,
PRIMARY KEY(transactionId,usrId,cdCode),
FOREIGN KEY(usrId) REFERENCES users(userId),
FOREIGN KEY(cdCode) REFERENCES cds(code)
);
它打印的内容如下:
> purchaseId cdName quantity price date status
> 1e963a1d CdName 1 price 2015-12-12:14:08 Pending
> 1e963a1d CdName 1 price 2015-12-12:14:08 Pending
> 1e963a1d CdName 1 price 2015-12-12:14:08 Pending
> 1e963a1d CdName 1 price 2015-12-12:14:08 Pending
> 1f2b8183 CdName 1 price 2015-12-12:14:20 Pending
> 1f2b8183 CdName 1 price 2015-12-12:14:20 Pending
> 1f2b8183 CdName 1 price 2015-12-12:14:20 Pending
我想通过purchaseId将购买分组到不同的表中,以计算每次购买的总成本。
答案 0 :(得分:0)
您可以将GROUP BY
与现有查询一起使用,例如
SELECT t.*, SUM(t.price) as total_price
FROM transactions t
INNER JOIN cds c ON t.cdCode = c.code
WHERE t.usrId = '$userId'
GROUP BY t.purchaseId
ORDER BY transactionId;