简体   繁体   English

带有IF语句并带有Count和SubQuery Select的MySQL

[英]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 我有以下sql语句,其中有一个IF语句和子查询环绕

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

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. 如果invoice_items表中有记录,它将设置billed标记。 MySQL treats booleans as integers, so the if is unnecessary. MySQL将布尔值视为整数,因此if是不必要的。 The exists should perform better. exists应该表现更好。 For the best performance, you want indexes on: invoice_item(chargeid) and charges(customerid, status) . 为了获得最佳性能,您需要索引: invoice_item(chargeid)charges(customerid, status)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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