为每个符合条件的用户求和(数量 x 值)后的 5 个最大总数

Find 5 greatest totals after summing (quantity x value) for each qualifying user

我目前有一个 table 可以显示用户的库存值。它有效,但它以随机顺序显示 所有 用户及其库存值。我只想将 table 限制为前 5 个降序库存值。

此数据跨越三个 table:DB Fiddle

  1. 用户
  2. 库存(用户库存中的每个项目都包含一行)
  3. 项(包含项的值)
echo "<table>
<th>Inventory Value</th>
<th>Username</th>";

// Choose the users we want (verified users).
$refineUsers=$db->query("SELECT userID FROM users WHERE accountVerified = 'true'");
while($users=$db->fetch_row($refineUsers)) {
  // Fetch the inventories of the users we want.
  $fetchInventories=$db->query("SELECT * FROM inventories WHERE userID = '".$users['userID']."'");
  $totalInventoryValue=0;
  while($inventories=$db->fetch_row($fetchInventories)) {
    // Fetch the values of the items.
    $fetchItemsData=$db->query("SELECT value FROM items WHERE itemID = '".$inventories['itemID']."'");
    while($items=$db->fetch_row($fetchItemsData)) {
      // Calculate the values of the various items within the user's inventory.
      $totalItemsValue=($items['value'] * $inventories['quantity']);
      // Calculate the total value of the user's inventory.
      $totalInventoryValue+=$totalItemsValue;
    }
  }
  // Display the values of each user's inventory.
  echo "<td>".money_format($totalInventoryValue)."</td>";
  echo "<td>".username($users['userID'])."</td>";
  echo "<tr>";
}

echo "</table>";

输出类似于:

Inventory Value Username
120000 Account1
112000 Accounts2
70000 Account3
169000 Accounts5

我猜想这可以通过 JOIN 查询来完成,但我不是很有经验,之前也没有做过跨越三个 table 的查询。我不知道如何使用这些嵌套查询来获取前 5 个库存总数并将它们按降序排列。

  1. 加入三个table是按照你原来嵌套查询的规则。
  2. 根据用户名值对数据进行分组。
  3. 这将创建需要在 SUM() 函数中组织的聚合数据,以便项目数量与正确的项目值相关联。
  4. 现在可以轻松应用您的 ORDER BY 和 LIMIT 规则。

SQL: (Demo)

SELECT username,
       SUM(
           IF(
               inventoryItemID = itemID,
               inventoryQuantity * itemValue,
               0
           )
       ) AS total
FROM users
JOIN inventory ON userID = inventoryUserID
JOIN items ON inventoryItemID = itemID
WHERE accountVerified = 'true'
GROUP BY username
ORDER BY total DESC
LIMIT 5