Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is how I would write it. The first query gets all keywords that must be in all 4 projects 1, 2, 3 and 4 via qualifier of project 1 keywords and JOIN to other for 2, 3 and 4. If you want a minimum of project 1 and ANY of 2, 3 or 4, I would change it slightly.</p> <p>From that, only then join to results and to the years table. Now, to help on optimization. Your keywords table should have an index on ( id, projects_id ). Results table should have an index on (keywords_id, country, user ) -- the country and user to help in the group by.</p> <pre><code>select STRAIGHT_JOIN r.country, r.user, SUM( y.january + y.february + y.march + y.april + y.may + y.june + y.july + y.august + y.september + y.october + y.november + y.december ) as AllMonths from ( SELECT k.id FROM keywords k JOIN keywords k2 on k.id = k2.id AND k2.project_id = 2 JOIN keywords k3 on k.id = k3.id AND k3.project_id = 3 JOIN keywords k4 on k.id = k4.id AND k4.project_id = 4 where k.project_id = 1 ) KeywordsInAll JOIN results r ON KeywordsInAll.ID = r.keywords_id JOIN `year` y ON r.id = y.results_id group by r.country, r.user </code></pre> <p>I changed the inner query to START with keywords AT LEAST from project 1... No sense in querying 10,000 keywords if project 1 only has 15 keywords (exaggerated, but example)</p> <p>From your posted comment, I would just change the prequery to almost exact as yours, but keep in first position and retain the "STRAIGHT_JOIN"</p> <pre><code> ( SELECT DISTINCT k.id FROM keywords k JOIN keywords k2 on k.id = k2.id AND k2.project_id IN (2, 3, 4 ) where k.project_id = 1 ) KeywordsInAll </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload