0

I'm trying to assign a variable a value based on a subquery in the where statement. The problem is that it doesn't work in php but in the workbench the query runs fine. I don't get any errors in php and it returns the correct pay ids but the variable field returns empty.

SELECT pay_id, @available AS amount_available
FROM tblpayments payments
WHERE customer_id = 9
AND (
    @available := (pay_amount - (
        SELECT if(sum(applied_amount) IS NULL, 0, sum(applied_amount))
        FROM tblxref_pmt_chg xref WHERE xref_pay_id = payments.pay_id
    ))
) > 0
6
  • 4
    can you post your php code? Commented Dec 18, 2013 at 15:55
  • 2
    PROTIP: IFNULL(sum(applied_amount), 0) :-) Commented Dec 18, 2013 at 15:59
  • 2
    PROPROTIP: COALESCE(SUM(applied_amount), 0) (SQL standard, whereas IFNULL() is MySQL specific). Commented Dec 18, 2013 at 16:05
  • 1
    @eggyal: Forgot about COALESCE. It's actually got another cool feature too. It accepts infinite parameters and will return the 1st non-NULL one! :-D Commented Dec 18, 2013 at 16:07
  • 1
    Do you really need to use variables (@available) here? Maybe you could convert this into a JOIN? Commented Dec 18, 2013 at 16:09

1 Answer 1

3

Why not try using a JOIN instead of a subquery/variable?

Something like this:

SELECT pay_id, (pay_amount - COALESCE(SUM(applied_amount), 0)) AS amount_available
FROM tblpayments payments
LEFT JOIN tblxref_pmt_chg xref ON xref_pay_id = payments.pay_id
WHERE customer_id = 9
GROUP BY payments.pay_id
HAVING amount_available > 0
Sign up to request clarification or add additional context in comments.

5 Comments

@eggyal: I guess I need more coffee... LEFT JOIN + COALESCE is probably the way to go. Thanks for pointing out my mistakes :)
Thanks @RocketHazmat your join idea works perfectly.
@eggyal COALESCE wasn't superfluous now that it's a LEFT JOIN. And even before, nothing indicates that applied_amount can't be null.
You're welcome! :-) Also, thanks to @eggyal for fixing it up :D
@rsanchez: Whoa. My bad. Eats humble pie

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.