Sharan De Silva
Sharan De Silva

Reputation: 608

Update table based on subquery with if condition

I want to achieve something like this:

update bill b set b.isPaid = (if(select count(*) from bill_payment p where p.bill_id = b.id) > 0,true,false);

but I get this error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select count(*) from res_bill_payment p where p.bill_id = b.id) > 0,true,false)' at line 1

How can I do it in mySQL?

Upvotes: 0

Views: 57

Answers (4)

sagi
sagi

Reputation: 40481

You can also do it with UPDATE..JOIN.. :

UPDATE bill b
LEFT JOIN (SELECT bill_id FROM bill_payment GROUP BY bill_id) bp
 ON(bp.bill_id = b.id)
SET b.isPaid = if(bp.bill_id IS NULL , 1 , 0 )

Upvotes: 0

clinux
clinux

Reputation: 3074

UPDATE bill b
SET b.isPaid = true
    WHERE
          (SELECT count(*)
           FROM bill_payment p
           WHERE p.bill_id = b.id) > 0;

Would do the trick

Or

UPDATE bill b
SET b.isPaid = 
          (SELECT count(*)
           FROM bill_payment p
           WHERE p.bill_id = b.id) > 0;

If you want to update EVERY row.

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269543

I would suggest writing this using EXISTS:

UPDATE bill b
    SET b.isPaid = (EXISTS (SELECT 1
                            FROM bill_payment p
                            WHERE p.bill_id = b.id
                           ) 
                   );

The EXISTS clause returns a boolean, so there is no need to explicitly use TRUE and FALSE (unless you really, really want to).

I strongly recommend using EXISTS instead of COUNT(*) for this purpose, because it often has much better performance. EXISTS can stop at the first matching record, instead of having to count all matching records.

Upvotes: 2

ignasi
ignasi

Reputation: 443

Seems you are missing some parenthesis:

UPDATE bill b 
SET b.isPaid = (IF(
                  (
                    SELECT COUNT(*) 
                    FROM bill_payment p 
                    WHERE p.bill_id = b.id
                  ) > 0
                  ,TRUE
                  ,FALSE
                ));

Upvotes: 1

Related Questions