MySQL带有IF语句,带有Count和SubQuery Select

时间:2014-09-01 02:16:14

标签: mysql sql performance

我有以下sql语句,它有一个IF语句和Subquery环绕它

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'

但我无法理解

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

还有其他方法可以提高效率和查询优化吗? EXPLAIN返回以下内容

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

1 个答案:

答案 0 :(得分:1)

您可以将其写为:

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';

如果billed表中有记录,则设置invoice_items标志。 MySQL将布尔值视为整数,因此if是不必要的。 exists应该表现得更好。为获得最佳性能,您需要索引:invoice_item(chargeid)charges(customerid, status)