MySQL Group By to display latest result

99封情书 提交于 2019-11-28 02:19:59

问题


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.


回答1:


SELECT  *
FROM    (
        SELECT  DISTINCT meta_value
        FROM    postdata pd
        WHERE   pd.meta_key = 'date'
        ) pd
JOIN    post p
ON      p.id = 
        (
        SELECT  post_id
        FROM    postdata pdi
        JOIN    post pi
        ON      pi.id = pdi.post_id
        WHERE   pdi.meta_key = 'date'
                AND pdi.meta_value = pd.meta_value
        ORDER BY
                pi.post_date DESC, pi.id DESC
        LIMIT 1
        )


来源:https://stackoverflow.com/questions/4668902/mysql-group-by-to-display-latest-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!