1

我在使用左连接 SQL 查询时遇到问题,但不明白为什么它不起作用。我有 3 个表:客户、采购和付款,我正在尝试选择总采购成本低于总付款的客户(即他们的余额大于 0)。

到目前为止,我有以下内容:

表:

Customers

id | Name


Purchases

id | customerid | cost


Payments

id | customerid | paymentamount 

SQL查询:

SELECT  a.*, 
COALESCE(b.totalCost , 0) as totalCost, 
COALESCE(c.totalPayments , 0) as totalPayments, 
COALESCE(b.totalCost , 0) - COALESCE(c.totalPayments , 0) AS Balance 
FROM customers a 
LEFT JOIN (SELECT  customerid, SUM(cost) AS totalCost FROM purchases GROUP BY customer) b ON a.id = b.customerid 
LEFT JOIN (SELECT customerid, SUM(paymentamount) AS totalPayments FROM payments GROUP BY customerid) c ON a.id = c.customerid 
WHERE Balance > 0"

当我运行查询时,即使我已经定义了 Balance,我也会在“where 子句”中收到错误“Unknown column 'Balance'”。

任何帮助深表感谢。谢谢!

4

2 回答 2

3

因为BALANCE是在表达式上给出的别名。在子句上使用表达式WHERE而不是ALIAS

WHERE   COALESCE(b.totalCost , 0) - COALESCE(c.totalPayments , 0) > 0

另一种方法是用子查询包装整个语句,以便您可以WHERE在外部查询的子句上使用别名。

您不能在子句ALIAS的同一级别上使用创建的原因WHERE是因为WHERE子句比创建的SELECT子句先执行ALIAS

下面是 SQL 的操作顺序:

  • FROM 子句
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • 选择子句
  • ORDER BY 子句
于 2013-05-18T13:44:06.967 回答
2

不幸的是,您不能在定义别名的同一“级别”上引用别名。

您需要将所有内容包装到派生表中:

select *
from (
   <your query goes here>
) t
where balance > 0
于 2013-05-18T13:43:45.153 回答