从MySQL WordPress中选择最后一行

omvjsjqw  于 2023-03-22  发布在  Mysql
关注(0)|答案(2)|浏览(173)

我试图获得最后一行与查询MySQL WordPress,查询是多少后标题与标题德国每个月,我如何才能扭转结果?
质询:

SELECT COUNT( p.id ) post_count, DATE_FORMAT( post_date,  '%Y-%m' ) post_month
FROM  `wp_posts` p
WHERE post_status =  'publish'
AND post_type = 'post'
AND post_title = 'Germany'
GROUP BY post_month
ORDER BY id DESC
LIMIT 3;

现在结果:

46 2023-03
130 2023-02
51 2023-01

我需要相反的结果:

51 2023-01
130 2023-02
46 2023-03

我从这里尝试子查询:Select last N rows from MySQL
但都不管用。
谢谢你们
在WordPress上获取MySQL查询的反向结果

qnzebej0

qnzebej01#

您需要按日期订购而不是按id订购

CREATE TABLE Table1
    (`count_` int, `date_` varchar(7))
;
    
INSERT INTO Table1
    (`count_`, `date_`)
VALUES
    (46, '2023-03'),
    (130, '2023-02'),
    (51, '2023-01')
;
Records: 3  Duplicates: 0  Warnings: 0
SELECT * FROM Table1 ORDEr By `date_`

| 计数--|日期_|
| - ------|- ------|
| 五十一|二○二三年一月|
| 一百三十|二○二三年二月|
| 四十六|二○二三年三月|
fiddle
所以用

SELECT COUNT( p.id ) post_count, DATE_FORMAT( post_date,  '%Y-%m' ) post_month
FROM  `wp_posts` p
WHERE post_status =  'publish'
AND post_type = 'post'
AND post_title = 'Germany'
GROUP BY post_month
ORDER BY post_month
LIMIT 3;

如果前面的查询没有给予正确答案,则使用

SELECT post_count, post_month
FROM
    (SELECT COUNT( p.id ) post_count, DATE_FORMAT( post_date,  '%Y-%m' ) post_month
    FROM  `wp_posts` p
    WHERE post_status =  'publish'
    AND post_type = 'post'
    AND post_title = 'Germany'
    GROUP BY post_month
    ORDER BY id
    LIMIT 3) t1
ORDER By post_month
ny6fqffe

ny6fqffe2#

从您的预期结果来看,在我看来,您似乎试图按post_month列升序排序。
所以我认为你要找的查询应该是:

SELECT COUNT( p.id ) post_count, DATE_FORMAT( post_date,  '%Y-%m' ) post_month
FROM  `wp_posts` p
WHERE post_status =  'publish'
AND post_type = 'post'
AND post_title = 'Germany'
GROUP BY post_month
ORDER BY post_month ASC
LIMIT 3;

相关问题