I have a discount table (productdiscounts) where I inserted product ID and the accounts that I wish to give discount. eg all users under ABC account should be given a discount of 10% and users under account XZS should be given a discount of 90%, etc.
secondly I selected all the available accounts and the discounts associated to them as alldiscounts for staff to see which accounts have discount on a product.
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,
'\"%')
Is that fishing around in a JSON string? Can't you supply the whole accountID so you don't have to do the slow LIKE
with a leading wild card?
With =
instead of LIKE
, this might help the first subquery:
INDEX(branchID, isActive, productID, AccountID, discount)
It might be more practical to do
SELECT COALESCE(MAX(discount), 0) ...
instead of the ORDER BY discount DESC LIMIT 1
.
The other parts may benefit from
patients: INDEX(billingAccounts)
productdiscounts: INDEX(accountID)
Please provide SHOW CREATE TABLE
and EXPLAIN SELECT...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.