简体   繁体   中英

MySQL with IF statment with a Count and SubQuery Select

I have following sql statement which has a IF statement and Subquery wrap around it

SELECT
                ch.*,
                IF (

                        (
                            SELECT COUNT(*)
                            FROM invoice_items ii
                            WHERE
                                ii.chargeid = ch.chargeid
                        ) > 0, 1, 0
                ) AS billed
              FROM charges ch
              WHERE
                ch.customerid = %s

                AND ch.status!='completed'

But i am unable to understand the part of

               (
                    SELECT COUNT(*)
                    FROM invoice_items ii
                    WHERE
                        ii.chargeid = ch.chargeid
                ) > 0

Also is there any other way do the same thing with a better efficiency and Query optimization ? EXPLAIN returns the following

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
1   PRIMARY     ch  ref     customerid,customer_service_idx     customerid  4   const   13  Using where
2   DEPENDENT SUBQUERY  ii  ref     chargeid    chargeid    4   ch.chargeid     1   Using index

You can write this as:

SELECT ch.*,
       (EXISTS (SELECT 1 FROM invoice_items ii WHERE ii.chargeid = ch.chargeid
               )
       ) as billed
FROM charges ch
WHERE ch.customerid = %s AND ch.status <> 'completed';

It is setting the billed flag if there is a record in the invoice_items table. MySQL treats booleans as integers, so the if is unnecessary. The exists should perform better. For the best performance, you want indexes on: invoice_item(chargeid) and charges(customerid, status) .

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