2014-09-01 80 views
0

我有以下这周围有的MySQL与IF具有计数和子查询选择statment

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 
的部分IF语句和子查询包裹的SQL语句

还有没有其他方式做更好的效率和查询优化同样的事情? 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

这是你可以写:

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)