aha, i see that it is post_parent that identifies the relationship
try this --
Code:
SELECT wp_posts_3.ID
, wp_posts_3.post_date
, wp_posts_3.post_title
, wp_posts_3.post_content
, last_image.guid AS last_image_guid
FROM wp_posts_3
INNER
JOIN ( SELECT post_id
, MAX(CASE WHEN meta_key = 'ad_city' THEN meta_value END ) AS ad_city
, MAX(CASE WHEN meta_key = 'ad_state' THEN meta_value END ) AS ad_state
, MAX(CASE WHEN meta_key = 'ad_trade_for' THEN meta_value END ) AS ad_trade_for
, MAX(CASE WHEN meta_key = 'ad_trade_category' THEN meta_value END ) AS ad_trade_category
, MAX(CASE WHEN meta_key = 'ad_miles_range' THEN meta_value END ) AS ad_miles_range
, MAX(CASE WHEN meta_key = 'ad_zip_code' THEN meta_value END ) AS ad_zip_code
, MAX(CASE WHEN meta_key = 'ad_price' THEN meta_value END ) AS ad_price
FROM wp_postmeta_3
GROUP
BY post_id
HAVING MAX(CASE WHEN meta_key = 'ad_miles_range' THEN meta_value END) = '50'
AND MAX(CASE WHEN meta_key = 'ad_state' THEN meta_value END) = 'NJ'
) AS q1
ON q1.post_id = wp_posts_3.ID -- note no parentheses
LEFT OUTER
JOIN ( SELECT post_parent
, MAX(post_date) AS latest
FROM wp_posts_3
WHERE post_status = 'inherit'
AND post_type = 'attachment'
AND post_mime_type = 'image/jpeg'
GROUP
BY post_parent
) AS q2
ON q2.post_parent = wp_posts_3.ID -- note no parentheses
LEFT OUTER
JOIN wp_posts_3 AS last_image
ON last_image.post_parent = wp_posts_3.ID -- note no parentheses
AND last_image.post_status = 'inherit'
AND last_image.post_type = 'attachment'
AND last_image.post_mime_type = 'image/jpeg'
AND last_image.post_date = q2.latest
WHERE wp_posts_3.post_status = 'publish'
ORDER
BY wp_posts_3.post_date DESC LIMIT 30
you can see i've pushed all that MAX business with the HAVING clause to determine eligibility into a subquery, q1, so that the outer query (which now deals with something else as well) doesn't have the GROUP BY on it
subquery q2 finds the latest image date for each post (using a LEFT OUTER JOIN in case a post doesn't have any images), and then an additional join is needed to retrieve the row (and the guid) that corresponds to that latest date
Bookmarks