0

I have a query which when run provides a satisfactory result, this query is as follows: -

SELECT DISTINCT(cp.payment_ref),COUNT(cp.status) as 'Amount Declined',cp.*
                FROM client_payments as cp
                WHERE DATE(cp.payment_date) = CURDATE()
                GROUP BY cp.payment_ref
                HAVING COUNT(cp.status='Declined')=3

What I want to do is update the results of the query with a tag, so what I need to do is turn the query into an update query which will update the result set. I cant get it to work.. here is my best attempt

UPDATE client_payments SET retry_status = 'retry' WHERE id=(SELECT cp.id ,COUNT(cp.status)
                FROM client_payments as cp
                WHERE DATE(cp.payment_date) = '2018-09-24'
                GROUP BY cp.payment_ref
                HAVING COUNT(cp.status='Declined')=3)

This throws an error of #1093 - You can't specify target table 'client_payments' for update in FROM clause

Any ideas?

Keith Ivison
  • 387
  • 4
  • 11

2 Answers2

0

you need from Clause :

UPDATE client_payments SET client_payments.retry_status = 'retry' 
from(SELECT cp.id ,COUNT(cp.status)
            FROM client_payments as cp
            WHERE DATE(cp.payment_date) = '2018-09-24'
            GROUP BY cp.payment_ref
            HAVING COUNT(cp.status='Declined')=3) as myquery
WHERE client_payments.id=myquery.id
Mohammad
  • 1,549
  • 1
  • 15
  • 27
0

So the solution that works is as follows: -

UPDATE client_payments as cp1
INNER JOIN (SELECT cp.id ,COUNT(cp.status)
        FROM client_payments as cp
        WHERE DATE(cp.payment_date) = '2018-09-24'
        GROUP BY cp.payment_ref
        HAVING COUNT(cp.status='Declined')=3) as cp2 on cp1.id = cp2.id
SET cp1.retry_status = 'retry'

Thanks to Mohammad for the nudge and mellamokb in this post for the inspiration.

Keith Ivison
  • 387
  • 4
  • 11