$usersQuery = 'SELECT user, budget FROM users';
$usersResult = mysqli_query($link, $usersQuery);
while($usersRow = mysqli_fetch_assoc($usersResult)) {
  $user = $usersRow['user'];
  $budget = $usersRow['budget'];
  $spendingsQuery = "SELECT SUM(`cost`) AS spent FROM spendings WHERE user = '$user'";
  $spendingsResult = mysqli_query($link, $spendingsQuery);
  $spendingRow = mysqli_fetch_assoc($spendingsResult);
  $spent = $spendingRow['spent'];
  $innerTaleRows .= "<tr><td>$user</td><td>$budget</td><td>$spent</td></tr>";
}

最佳答案

是:

SELECT users.user AS user,
       users.budget AS budget,
       SUM(spendings.cost) AS spent
FROM users

LEFT OUTER JOIN spendings
ON spendings.user = users.user

GROUP BY users.user, users.budget

关于mysql - 这两个选择可以粉碎成一个吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6795558/

10-11 12:44