Skip to content
Advertisement

Mysql Inner Select Optimization

I have a following mysql query which consists some inner select operations. But it is to slow to get output from that query..

SELECT 
            c.topicName as 'topicName',
            c1 as 'sumOfWordsInTopic',
            c.word,
            c.wordCount,
            c2/c1 AS 'wordProbability'
            FROM weightallofwordsintopic as c
            JOIN (
            SELECT topicName, sum(wordCount) AS 'c1'
            FROM weightallofwordsintopic group by topicName 
            ) AS sub1 ON c.topicName = sub1.topicName 
            JOIN (
            SELECT topicName,word, wordCount AS 'c2'
            FROM weightallofwordsintopic 

            ) AS sub2 ON c.topicName = sub2.topicName and  c.word=sub2.word

First inner select takes sum of wordCounts and second one takes wordcounts and the outer select take division of them. Is there any way to make it a bit more faster ? Thanks for your interest..

Advertisement

Answer

First, I’m not sure why you have a second subquery. I think this should do what you want:

SELECT wwt.topicName, t.topic_cnt as sumOfWordsInTopic,
       wwt.word, wwt.wordCount,
       (wwt.word / t.topic_cnt) AS wordProbability
FROM weightallofwordsintopic as wwt JOIN
     (SELECT topicName, sum(wordCount) AS topic_cnt
      FROM weightallofwordsintopic 
      GROUP BY topicName 
     ) t
     ON wwt.topicName = t.topicName;

This will speed up the query a bit.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement