繁体   English   中英

当我在 concat 或 group_concat 中使用 select 并且我想以 JSON 的形式返回它们时,我的查询很慢。 我怎样才能让它更快?

[英]My query is slow when ever I select inside concat or group_concat and I want to return them in form of JSON. how can I make it faster?

我有一个折扣表(productdiscounts),我在其中插入了产品 ID 和我希望给予折扣的帐户。 例如,ABC 账户下的所有用户都应该享受 10% 的折扣,XZS 账户下的用户应该享受 90% 的折扣等。

其次,我选择了所有可用的帐户以及与其关联的折扣作为 alldiscounts,供员工查看哪些帐户对产品有折扣。

 SELECT 
      products.manufacturer as manufacturerID, stock.expiryDate,
      *coalesce((select discount from productdiscounts where(productID=products.id and branchID=? and isActive='1' and patients.billingAccounts like concat('%\"',productdiscounts.accountID,'\"%')) order by discount desc limit 1),0.00) as discount*,
     **concat('[',(select 
    group_concat('{\"productID\":\"',productdiscounts.productID,'\",\"accountID\":\"',productdiscounts.accountID,'\",\"discount\":\"',productdiscounts.discount,'\",\"accountName\":\"',accounts.name,'\",\"accountNo\":\"',accounts.accountNo,'\"}') from productdiscounts 
    left join accounts on(productdiscounts.accountID=accounts.id)
    where(productdiscounts.productID=products.id and productdiscounts.branchID = ? and productdiscounts.isActive = '1' )),']') as allDiscounts**
    from products 
and  patients.billingAccounts like concat('%\"',productdiscounts.accountID,
                                        '\"%')

那是在 JSON 字符串中钓鱼吗? 您不能提供整个 accountID,这样您就不必使用前导通配符进行缓慢的LIKE吗?

使用=而不是LIKE ,这可能有助于第一个子查询:

INDEX(branchID, isActive, productID, AccountID, discount)

这样做可能更实际

 SELECT COALESCE(MAX(discount), 0) ...

而不是ORDER BY discount DESC LIMIT 1

其他部分可能受益于

patients:  INDEX(billingAccounts)
productdiscounts:  INDEX(accountID)

请提供SHOW CREATE TABLEEXPLAIN SELECT...

暂无
暂无

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

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