0

How Can i reduce this query run time with any type of join or sub-query or nested query.

select 
`p`.`id`,
`p`.`name`,
SUM(s.quantity) as inst,
from `product` as `p` 
LEFT JOIN  sales as s ON s.pid=p.`id` AND s.sales_id IN (SELECT invoice.invoice_id FROM invoice WHERE invoice.ccid NOT IN (SELECT ccid FROM ticket WHERE st='1'))
where `p`.`hc` = '1' 
GROUP BY `p`.`id` 
order by `p`.`name` DESC 
3
  • 1
    use inner join instead on in query and left join instead of not in .....that will reduce query time because in query take much time Commented Jun 10, 2016 at 9:15
  • select p.id, p.name AS name, SUM(ss.instock) as inst from product as p LEFT JOIN (SELECT s.id,s.pid,CASE COUNT(crt.salvage_part) WHEN 1 THEN 0 ELSE s.quantity END AS instock FROM sales as s LEFT JOIN invoice as i ON i.invoice_id=s.sales_id LEFT JOIN crt ON crt.cc_id=i.cc_id AND crt.st='1' GROUP BY s.id) as ss ON ss.pid=p.id where p.hc = '1' GROUP BY p.id order by p.name DESC Tried This Too, But Can't Reduce it's runtime. Commented Jun 10, 2016 at 9:23
  • The question is nonsensical as, clearly, this query would produce a syntax error. Commented Jun 11, 2016 at 14:12

2 Answers 2

1

Add index on st from ticket and also add index on ccid from invoice and sales_id from sales.

Try using Explain clause before your query whether created index is being used or not in possible_keys column output .

Sign up to request clarification or add additional context in comments.

2 Comments

Please explain what you mean. with example if possible.
Not Working using index
0

Finally i come to a solution & it works

select 
s.pid,
SUM(s.quantity) AS squan 
from invoice as i 
LEFT JOIN sales as s ON s.sales_id=i.invoice_id
LEFT JOIN crt ON crt.cc_id=i.cc_id AND crt.ch='0'
WHERE 
crt.ch='0' 
AND 
(i.cc_id!='' OR i.cc_id!='0') 
GROUP BY i.invoice_id 

1 Comment

You SELECT pid, but GROUP BY invoice_id. This is liable to provide an indeterminate/erroneous result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.