SQL Query with LEFT JOIN Issue

前端 未结 2 1722
Happy的楠姐
Happy的楠姐 2021-01-24 05:45

I am having problems with a left join SQL query but can\'t see why it isn\'t working. I have 3 tables: customers, purchases and payments, and i\'m trying to select customers who

2条回答
  •  忘了有多久
    2021-01-24 06:19

    because BALANCE is an ALIAS given on the expression. Use the expression on the WHERE clause instead of the ALIAS

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

    the other way is to wrap the whole statement with a subquery so you can use the alias on the WHERE clause of the outer query.

    The reason why you cannot use ALIAS that is created on the same level of the WHERE clause is because WHERE clause executes first than the SELECT clause where the ALIAS is created.

    Here's the SQL Order of Operation:

    • FROM clause
    • WHERE clause
    • GROUP BY clause
    • HAVING clause
    • SELECT clause
    • ORDER BY clause

提交回复
热议问题