我得到了以下sql语句:
$sql4 = "SELECT
customers_basket.customers_basket_quantity,
products.products_price
From
products Inner Join
products_description
On products.products_id = products_description.products_id Inner Join
customers_basket On customers_basket.products_id = products.products_id
Where
products_description.language_id = '".$lang."' And
customers_basket.customers_id = '".$cid."'";
现在问题出在sql查询之前,我不知道它会有多少结果。完成查询后我首先需要做的是:
customers_basket.customers_basket_quantity * products.products_price
然后我需要补充一下。所以上面的计算发生在每一行本身。然后我需要相互添加所有结果,所以我得到最终的总价格。我如何在我的PHP甚至MySql中这样做?
我读了这篇帖子Get all mysql selected rows into an array,但它并没有帮助我。
修改
更确切地说:
例如,我的查询给出了以下结果:
customers_basket.customers_basket_quantity | products.products_price
2 5
3 4
现在我需要做以下事情:
2 * 5 = 10
3 * 4 = 12
10 + 12 = 22
答案 0 :(得分:1)
只需您可以像这样更新您的查询:
$sql4 = "SELECT customers_basket.customers_basket_quantity, products.products_price,
(customers_basket.customers_basket_quantity * products.products_price) as total, (select sum(customers_basket.customers_basket_quantity * products.products_price) from products products Inner Join
customers_basket On customers_basket.products_id = products.products_id ) as total_sum
From
products Inner Join
products_description
On products.products_id = products_description.products_id Inner Join
customers_basket On customers_basket.products_id = products.products_id
Where
products_description.language_id = '".$lang."' And
customers_basket.customers_id = '".$cid."'";
当你循环结果时,你也可以用php进行求和。
答案 1 :(得分:1)
您可以使用SUM
:
"SELECT
SUM(customers_basket.customers_basket_quantity * products.products_price) as total
From
products Inner Join
products_description
On products.products_id = products_description.products_id Inner Join
customers_basket On customers_basket.products_id = products.products_id
Where
products_description.language_id = '".$lang."' And
customers_basket.customers_id = '".$cid."'";