这两个选择可以粉碎成一个吗?

时间:2011-07-22 20:10:26

标签: mysql

$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>";
}

3 个答案:

答案 0 :(得分:2)

是的,他们可以。

MySQL查询:

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

完整代码:

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

答案 1 :(得分:1)

是:

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

答案 2 :(得分:0)

$usersQuery = 'SELECT SUM(`cost`) as spent, users.user, users.budget AS spent FROM spendings INNER JOIN users on users.user=spendings.user GROUP BY users.user, users.budget';
$usersResult = mysqli_query($link, $usersQuery);
while($usersRow = mysqli_fetch_assoc($usersResult)) {
  $user = $usersRow['user'];
  $budget = $usersRow['budget'];
  $spent = $usersRow['spent'];
  $innerTaleRows .= "<tr><td>$user</td><td>$budget</td><td>$spent</td></tr>";
}