2016-09-26 33 views
0

我已經寫以下查詢:查詢來選擇行與列中的值而不是在其他

select case when edd.is_percent='Y' 
       then (((edd.dis_value/100) * c.paid_amount) - c.amount) 
      else (edd.dis_value - c.amount) 
     end as profit 
from used_balance_detail ubd 
inner 
join service_category_service_type scst 
on scst.id = ubd.service_category_service_type_id 
inner 
join service_category sc 
on sc.id = scst.service_category_id 
inner 
join epay_discount_details edd 
on sc.id = edd.service_category_id 
inner 
join commission c 
on c.used_balance_detail_id = ubd.id 
and c.subscriber_id not in (select distinct c.discount_given_to_id 
           from used_balance_detail ubd 
           inner join commission c 
           on c.used_balance_detail_id = ubd.id 
           where c.discount_given_to_id is not null) 
and scst.merchant_type = 'R' group by ubd.id asc; 

這給出了較小數據所需的結果。但我有5000 &以上的行,這變得太慢,得不到結果。 這個查詢是否可以修改以提供更快的結果?

+0

在子查詢中不需要該不同。 – jarlh

+0

您正在使用'ubd.id'進行分組,但可能會有多個'edd'記錄,那麼您希望選擇哪些記錄?您正在使用MySql的糟糕的非SQL標準功能,只是選擇了它喜歡的任何東西。我不認爲這些結果可能有意義。你應該指定你想從哪個'edd'記錄獲得信息,或者 - 如果你想要所有的信息彙總 - 指定一個聚合函數(比如'avg'或'sum',或'min',... ) – trincot

+0

@trincot謝謝你的建議。一行ubd可以有一個edd值。我不想要聚合值,但要計算ubd的每一行,以便可以將結果更新爲ubd的新列。 – rosun

回答

0
scst: INDEX(merchant_type, service_category_id, id) 
ubd: INDEX(service_category_service_type_id, id) 
edd: INDEX(service_category_id) 
c: INDEX(used_balance_detail_id) 

查找到改變not in (select distinct ...)成要麼not exists(select *...)LEFT JOIN

查詢有潛在的缺陷 - GROUP BY沒有列出select中的所有列,所以結果集可能是隨機的。請參閱https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_only_full_group_byhttps://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html

+0

謝謝@Rick James ... LEFT JOIN可以做到這一點 – rosun

相關問題