I’m trying to create a custom SELECT query to find my Personal Best races from WordPress Custom Types where the times are a custom meta field.
This is the query I used to select the posts. I’ve simplified it for debugging, but eventually I want to select several term slugs and find the MIN for each using GROUP BY:
SELECT t.slug,
p.ID,
p.post_date,
p.post_title,
m.meta_value as pb_mins
FROM $wpdb->posts p,
$wpdb->postmeta m,
$wpdb->term_relationships tr,
$wpdb->term_taxonomy tt,
$wpdb->terms t
WHERE p.ID = tr.object_id
AND p.ID = m.post_id
AND tr.term_taxonomy_id = tt.term_taxonomy_id
AND tt.term_id = t.term_id
AND p.post_type = 'runs'
AND m.meta_key = 'ssr_duration_min'
AND t.slug in ('10mi')
(I’m outputting the results to an array and using print_r to check it temporarily.)
This selects the two races/runs with the ’10mi’ term and displays the correct times/date/title for them.
The problem comes when I add the MIN function:
SELECT t.slug,
p.ID,
p.post_date,
p.post_title,
MIN(m.meta_value) as pb_mins
The correct (minimum) time is selected, but the other details (date, title) are from the OTHER 10mi run/race.
I’ve tried changing the FROM clause to use LEFT JOIN and also INNER JOIN but the same thing happens: it’s fine for selecting both ’10mi’ runs but gives the wrong output when I add the MIN function.
Thanks for any help you can offer. This is my first post here so please let me know if I need to add any more details.
I never got round to posting my solution to this. It’s been a while now, so I can’t fully remember how I even arrived at it (most likely trial and error) but if this helps anyone, they’re welcome to it. If I think of any more details, I’ll add them as comments to this answer.