I’m trying to order a grouped resultset. Problem is that one of the join conditions references another table. Specifically, I need to select records from table_a that have the highest value within a group, but the group id is a field in a different table.
Below are some of the things I tried, in different variations. Whenever I add GROUP BY pr.id, some results that know should be in the top 3, are excluded. When I do not add it I get more than 1 record per group.
Any help much appreciated.
SELECT * FROM ivalues AS iv
INNER JOIN mprod AS p ON (p.id = iv.p_id)
INNER JOIN contact AS pr ON (pr.id = p.pr_id)
LEFT OUTER JOIN ivalues i2
ON i2.p_id = p2.id
AND i2.period = iv.period
AND i2.current = iv.current
AND i2.cert = iv.cert
AND i2.exists = iv.exists
AND iv.value > i2.value
WHERE
iv.period = 0
AND iv.current = 1
AND iv.cert = 1
AND p.type_id = 15747
AND iv.exists = 1
AND i2.id IS NULL
GROUP BY pr.id
ORDER BY iv.value ASC
LIMIT 10;
SELECT * FROM ivalues AS iv
INNER JOIN mprod AS p ON (p.id = iv.p_id)
INNER JOIN contact AS pr ON (pr.id = p.pr_id)
LEFT OUTER JOIN contact pr2
ON pr2.id = p.pr_id
LEFT OUTER JOIN mprod p2
ON p2.type_id = p.type_id
LEFT OUTER JOIN ivalues i2
ON i2.p_id = p2.id
AND i2.period = iv.period
AND i2.current = iv.current
AND i2.cert = iv.cert
AND i2.exists = iv.exists
AND iv.value > i2.value
WHERE
iv.period = 0
AND iv.current = 1
AND iv.cert = 1
AND p.type_id = 15747
AND iv.exists = 1
AND i2.id IS NULL
ORDER BY iv.value ASC
LIMIT 10;
SELECT * FROM ivalues AS iv
INNER JOIN mprod AS p ON (p.id = iv.p_id)
INNER JOIN contact AS pr ON (pr.id = p.pr_id)
LEFT OUTER JOIN contact p2
ON p2.pr_id = p.pr_id
AND p2.type_id = p.type_id
INNER JOIN mprod p2
ON p2.type_id = p.type_id
INNER JOIN ivalues i2
ON i2.p_id = p2.id
AND i2.period = iv.period
AND i2.current = iv.current
AND i2.cert = iv.cert
AND i2.exists = iv.exists
AND iv.value > i2.value
WHERE
iv.period = 0
AND iv.current = 1
AND iv.cert = 1
AND p.type_id = 15747
AND iv.exists = 1
ORDER BY iv.value ASC
LIMIT 3;
I think you will need to join ivalues and mprod as a subselect, either as an outer join to exclude non-maximum values, or as an inner group to find the maximum value. Hopefully it looks something like this: