I have read here that MySQL processes ordering before applying limits. However, I receive different results when applying a LIMIT
parameter in conjunction with a JOIN
subquery. Here is my query:
SELECT
t1.id,
(t2.counts / c.matches)
FROM
table_one t1
JOIN
table_two t2 ON t1.id = t2.id
JOIN
(
SELECT
t1.id, COUNT(DISTINCT t1.id) AS matches
FROM
table_one t1
JOIN table_two t2 ON t1.id = t2.id
WHERE
t1.id IN (3390 , 3236, 148, 2811, 829, 137)
AND t2.value_one <= 30
AND t2.value_two < 2
GROUP BY t1.id
ORDER BY (t2.counts / matches)
LIMIT 0, 50 -- PROBLEM IS HERE (I think)
) c ON c.id = t1.id
ORDER BY (t2.counts / c.matches), t1.id;
Here is a rough description of what I think is happening:
- The sub-query selects a bunch of ids from
table_one
that meet the criteria - These are ordered by
(t2.counts / matches)
- The top 50 (in ascending order) are fashioned into a table
- This resulting table is then joined on the the id column
- Results are returned from the top level
JOIN
- without aGROUP BY
clause this time.table_one
is a reference table so this will return many rows with the same ID.
I appreciate that some of these joins don't make a lot of sense but I have stripped down my query for readability - it's normally quite chunky .
The problem is that when, I include the LIMIT
parameter I get a different set of results and not just the top 50. What I want to do is get the top results from the subquery and use these to join onto a bunch of other tables based on the reference table.
Here is what I have tried so far:
LIMIT
on the outer query (this is undesirable as this cuts off important information).- Trying different
LIMIT
tables and values.
Any idea what is going wrong, or what else I could try?