gpt4 book ai didi

MySQL Group By 显示最新结果

转载 作者:行者123 更新时间:2023-11-29 06:19:15 25 4
gpt4 key购买 nike

我正在尝试查询 MySQL 以 ORDER 然后 GROUP...这是一个在这里经常出现的问题,我找到了一个似乎与我相关的答案:Getting a MySQL group by query to display the row in that group with the highest value

但是我发现在进行分组之前它仍然没有排序。

具体来说,我想做的是使用 Wordpress 自定义帖子类型按名为“日期”的元数据字段进行分组,并按帖子日期排序。

这是我的查询:

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

所需的结果是每个“日期”的帖子(这是一个元字段),以及根据 post_date 的该“日期”的最新帖子。

最佳答案

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
)

关于MySQL Group By 显示最新结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4668902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com