gpt4 book ai didi

MySQL 带有带有 acCount 和 SubQuery Select 的 IF 语句

转载 作者:行者123 更新时间:2023-11-29 12:44:52 25 4
gpt4 key购买 nike

我有以下 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'

但是我无法理解这部分

               (
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

最佳答案

您可以将其写为:

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

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

关于MySQL 带有带有 acCount 和 SubQuery Select 的 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25598066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com