Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

wordpress - MySQL Group By to display latest result

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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
        )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...