SQL Query with LEFT JOIN Issue

前端 未结 2 1713
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
    0 讨论(0)
  • 2021-01-24 06:32

    Unfortunately you can't reference an alias on the same "level" where it's defined.

    You need to wrap everything into a derived table:

    select *
    from (
       <your query goes here>
    ) t
    where balance > 0
    
    0 讨论(0)
提交回复
热议问题