I'm trying to query MySQL to ORDER then GROUP... it's a question that comes up a lot here and I found an answer that seemed relevant to me: Getting a MySQL group by query to display the row in that group with the highest value
However I'm finding that it is still not ordering before doing the grouping.
Specifically what I'm trying to do is use Wordpress custom post types to group by a meta data field called 'date', ordered by the post date.
Here's my query:
SELECT
`ID`, `date`, `post_date`, `date_rank`
FROM (
SELECT
`Post`.`ID`,
`Post`.`post_date`,
`PostData`.`meta_value` AS `date`,
CASE
WHEN @data_date = `PostData`.`meta_value` THEN @rowum := @rownum + 1
ELSE @rownum := 1
END AS date_rank,
@data_date := `PostData`.`meta_value`
FROM
`".$this->wpdb->posts."` AS `Post`
JOIN
`".$this->wpdb->postmeta."` AS `PostData`
ON `Post`.`ID` = `PostData`.`post_id` AND `PostData`.`meta_key` = 'date'
JOIN (SELECT @rownum := 0, @data_date := '') AS `vars`
WHERE
`Post`.`post_type` = 'my_post_type'
AND
`Post`.`post_status` = 'publish'
ORDER BY `Post`.`post_date` DESC
) AS `x`
WHERE date_rank = 1
ORDER BY `date` ASC
The desired results are a post for each 'date' (this is a meta field), with the latest post for this 'date' as per the post_date.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…