简体   繁体   中英

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?

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.

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
                ));
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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM