1

我有一个 mysql 查询,它从几行中减去金额以在名为“余额”的新列中显示新金额。我希望它只显示余额>'0'的那些记录。见下文:

    SELECT 
visits.visit_id,
visits.payment_increments,
((visits.total - visits.paid) - SUM(payments.amount)) AS Balance,
schedule.schedule_date
FROM
visits
    LEFT OUTER JOIN
schedule ON visits.schedule_id = schedule.id
    LEFT OUTER JOIN
payments ON visits.visit_id = payments.visit_id
WHERE
Balance>'0'
GROUP BY visits.visit_id

有没有办法在 WHERE 语句中使用我的新列?现在,它显示的只是一个错误-> 错误代码:1054 'where 子句'中的未知列'Balance'。

任何帮助深表感谢!

4

3 回答 3

2

使用HAVING而不是WHERE

GROUP BY ... HAVING Balance >0

注意: HAVING适用于非表列..由于Balance不是主表的列,所以这是一个虚构的列,所以它可以像使用表列HAVING一样工作WHERE

Read more...

于 2013-03-20T04:29:27.673 回答
1
  SELECT 
visits.visit_id,
visits.payment_increments,
((visits.total - visits.paid) - SUM(payments.amount)) AS Balance,
schedule.schedule_date
FROM
visits
    LEFT OUTER JOIN
schedule ON visits.schedule_id = schedule.id
    LEFT OUTER JOIN
payments ON visits.visit_id = payments.visit_id

GROUP BY visits.visit_id HAVING  Balance>'0'
于 2013-03-20T04:31:49.287 回答
0

您可以使用相同的 SQL 查询,只需提及完整的列名

   SELECT 
   visits.visit_id,
   visits.payment_increments,
   ((visits.total - visits.paid) - SUM(payments.amount)) AS Balance,
   schedule.schedule_date
  FROM
     visits
    LEFT OUTER JOIN
   schedule ON visits.schedule_id = schedule.id
   LEFT OUTER JOIN
  payments ON visits.visit_id = payments.visit_id
WHERE
  ((visits.total - visits.paid) - SUM(payments.amount))>'0'
 GROUP BY visits.visit_id
于 2013-03-20T05:14:33.683 回答