doudie2693 2016-11-28 21:46
浏览 73
已采纳

来自mysql的sum值

Using PHP, I can find the productId in the first table:

$stmt = $db->prepare("SELECT productId FROM boughtProducts WHERE userid = :username");
$stmt->execute(array(':username' => $_SESSION['username']));
$productId = $stmt->fetchAll();

I also have a columns with values in variables like the following:

$productId["0"]["productId"] & $productId["1"]["productId"]...

In the variables above I only get IDs where I must find my values in second table.

$stmt = $db->prepare("SELECT price FROM products WHERE id = :productid");
$stmt->execute(array(':productid' => $productId["0"]["productId"]));
$price = $stmt->fetch(PDO::FETCH_ASSOC);

This returns all numbers, which I want to SUM and store in a variable. How can I achieve this? I want to SUM price for all products which are bought by userid.

  • 写回答

1条回答 默认 最新

  • dougai3418 2016-11-28 22:11
    关注

    Something along these lines might work:

    SELECT SUM(products.price) FROM boughtProducts, products WHERE boughtProducts.userid = :username and products.id = boughtProducts.productId
    

    Read something about the JOIN keyword (I'm using an implicit join in my example)... also get yourself acquainted with the concept of foreign keys.

    Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM