EDIT TO CLARIFY
I am probably misunderstanding the use of GROUP BY
so I'll just rephrase my question without making assumptions on how to solve the problem:
I have a list of term_id
s and a table containing objects (which have an object_id
PK and term_id
as FK among other fields), I need to extract the object with the highest object_id
for every term_id
supplied. What's the correct way to do it?
ORIGINAL QUESTION
I'm sure I'm missing something obvious but I can't figure out how to specify which record will be returned by a query with a GROUP BY
. By default GROUP BY
returns the first record in the group, who can I get the last one instead without using a subquery?
Basic query returns first record:
SELECT *
FROM wp_term_relationships
WHERE term_taxonomy_id IN (20, 21, 22)
GROUP BY term_taxonomy_id
this works, but with a subquery
SELECT *
FROM (
SELECT *
FROM wp_term_relationships
WHERE term_taxonomy_id IN (20, 21, 22)
ORDER BY object_id DESC
) wtt
GROUP BY term_taxonomy_id
this is a syntax error
SELECT *
FROM wp_term_relationships
WHERE term_taxonomy_id IN (20, 21, 22)
ORDER BY object_id DESC
GROUP BY term_taxonomy_id