我有一个mysql查询,它从多行中减去金额,以在名为“Balance”的新列中显示新金额。我希望它只显示那些平衡>的记录。 '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'。
非常感谢任何帮助!
答案 0 :(得分:2)
使用HAVING
代替WHERE
GROUP BY ... HAVING Balance >0
注意: HAVING
适用于非表格列。由于余额不是主表的列,所以这是一个虚构的列,因此它可以与HAVING
一起使用,就像WHERE
适用于表格列
答案 1 :(得分: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'
答案 2 :(得分: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