查询 select 行的值在一列中但不在其他列中

query to select row with value in a column but not in other

我写了下面的查询:

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 以上的行,这变得太慢而无法获得结果。 是否可以修改此查询以提供更快的结果?

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_by and https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html