Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would do almost an inverse of what Jasper provided... Start your query with your criteria to explicitly limit the few items that MAY qualify instead of getting all items and running a sub-select on each entry. Could pose as a larger performance hit... could be wrong, but here's my offering..</p> <pre><code>select i2.* from ( SELECT i.id FROM items i WHERE i.issue_date &gt; 2011 AND i.listed = 1 AND i.state_id = 5 GROUP BY i.id HAVING AVG( i.price) &lt;= 500 ) PreQualify JOIN items i2 on PreQualify.id = i2.id AND i2.issue_date &gt; 2011 AND i2.listed = 1 AND i2.state_id = 5 order by i2.price desc limit 25 </code></pre> <p>Not sure of the order by, especially if you wanted grouping by item... In addition, I would ensure an index on (state_id, Listed, id, issue_date)</p> <p>CLARIFICATION per comments</p> <p>I think I AM correct on it. Don't confuse "HAVING" clause with "WHERE". WHERE says DO or DONT include based on certain conditions. HAVING means after all the where clauses and grouping is done, the result set will "POTENTIALLY" accept the answer. THEN the HAVING is checked, and if IT STILL qualifies, includes in the result set, otherwise throws it out. Try the following from the INNER query alone... Do once WITHOUT the HAVING clause, then again WITH the HAVING clause...</p> <pre><code>SELECT i.id, avg( i.price ) FROM items i WHERE i.issue_date &gt; 2011 AND i.listed = 1 AND i.state_id = 5 GROUP BY i.id HAVING AVG( i.price) &lt;= 500 </code></pre> <p>As you get more into writing queries, try the parts individually to see what you are getting vs what you are thinking... You'll find how / why certain things work. In addition, you are now talking in your updated question about getting multiple IDs and prices at apparent low and high range... yet you are also applying a limit. If you had 20 items, and each had 10 qualifying records, your limit of 25 would show all of the first item and 5 into the second... which is NOT what I think you want... you may want 25 of each qualified "id". That would wrap this query into yet another level...</p>
    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. This table or related slice is empty.
    1. 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