我的SQL查詢出現問題。我想按債務金額選擇記錄。金額通過與兩個表格的關係計算。嘗試在where子句中使用別名列名時發生錯誤
這工作得很好:
SELECT `i`.*,
(i.amount_netto + (i.amount_netto * i.vat/100)) - (SUM(p.amount_netto)) AS `debt`,
`e`.`name` AS `user_name`,
`e`.`surname` AS `user_surname`,
`c`.`name` AS `contractor_name`
FROM `invoices` AS `i`
INNER JOIN `payments` AS `p` ON i.id = p.invoice_id
INNER JOIN `employees` AS `e` ON i.employee_id = e.id
INNER JOIN `contractors` AS `c` ON i.contractor_id = c.id
GROUP BY `i`.`id`
ORDER BY `debt` ASC
但是當我通過debt
添加一個WHERE子句,我得到一個錯誤:
Unknown column 'debt' in 'where clause'
查詢看起來是這樣的:
SELECT `i`.*,
(i.amount_netto + (i.amount_netto * i.vat/100)) - (SUM(p.amount_netto)) AS `debt`,
`e`.`name` AS `user_name`,
`e`.`surname` AS `user_surname`,
`c`.`name` AS `contractor_name`
FROM `invoices` AS `i`
INNER JOIN `payments` AS `p` ON i.id = p.invoice_id
INNER JOIN `employees` AS `e` ON i.employee_id = e.id
INNER JOIN `contractors` AS `c` ON i.contractor_id = c.id
WHERE `debt` > 1
GROUP BY `i`.`id`
ORDER BY `debt` ASC
爲什麼我不能在WHERE子句中訪問debt
,但我可以在ORDER子句中使用?
你應該使用表的別名來訪問的債務,也可能是'p.debt'可能或您製作的其他別名。 – iphonic
我試圖使用p.debt並沒有任何反應。我仍然有一個錯誤:「在'where子句'''Unknown column'p.debt'' – dtx