MySQL wordpress 查询:每个类别至少 100 个帖子 - 删除其余的

MySQL query for wordpress: minimum 100 posts per category - delete the rest

我想要一个 SQL 语句,该语句将删除所有 post,除了每个类别中最近的 100 个。

这看起来很简单 - 但许多 post 存在于多个类别中,因此删除一个类别中的 post 编号 101 可能会删除另一个类别中的 post 编号 89。

我试过使用 MySQLs "LIMIT" 但它不允许在子查询中使用。因此,我尝试将 ROW_NUMBER() OVERrownumber >= 100 一起使用,这在子查询中有效 - 但给出了错误的结果。

所以这适用于选择类别中早于最后 100 个的所有 post:

SELECT * FROM (
  SELECT
    ROW_NUMBER() OVER (ORDER BY wp_posts.post_date DESC) AS rownumber
  FROM wp_posts
  WHERE (wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (71) ) ) 
AND (wp_posts.post_type = 'post' OR wp_posts.post_type = 'xdays1')  
) AS foo
WHERE rownumber >= 100

得到正确数量的结果,29,602。

但是当我把它放在另一个查询中时,结果是错误的:

SELECT wp_posts.*
FROM  wp_posts 
   WHERE 
wp_posts.ID IN

(SELECT * FROM (
  SELECT
    ROW_NUMBER() OVER (ORDER BY wp_posts.post_date DESC) AS rownumber
  FROM wp_posts
  WHERE (wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (71) ) ) 
AND (wp_posts.post_type = 'post' OR wp_posts.post_type = 'xdays1')  
) AS foo
WHERE rownumber >= 100)

结果只有 10 行。 此测试仅适用于一个类别,我想对所有类别都执行此测试 - 所以我想如果我可以在子查询中使用它,我可以添加其他类别。

我做错了什么?

设法让它工作。这是使用 ID 为 71、72、73、74

的四个类别
SELECT wp_posts.*
FROM  wp_posts 
   
WHERE 

(wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish')   
   
AND

-- posts discluded if under 100 most recent per category:
(

( wp_posts.ID NOT IN (SELECT ID FROM (SELECT ID, ROW_NUMBER() OVER (ORDER BY wp_posts.post_date DESC) AS rownumber
  FROM wp_posts
  WHERE (wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (71) ) ) 
AND (wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish')  
) AS foo
WHERE rownumber <= 100
) 
)

AND

( wp_posts.ID NOT IN (SELECT ID FROM (SELECT ID, ROW_NUMBER() OVER (ORDER BY wp_posts.post_date DESC) AS rownumber
  FROM wp_posts
  WHERE (wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (72) ) ) 
AND (wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish')  
) AS foo
WHERE rownumber <= 100
) 
)

AND

( wp_posts.ID NOT IN (SELECT ID FROM (SELECT ID, ROW_NUMBER() OVER (ORDER BY wp_posts.post_date DESC) AS rownumber
  FROM wp_posts
  WHERE (wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (73) ) ) 
AND (wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish')  
) AS foo
WHERE rownumber <= 100
) 
)

AND

( wp_posts.ID NOT IN (SELECT ID FROM (SELECT ID, ROW_NUMBER() OVER (ORDER BY wp_posts.post_date DESC) AS rownumber
  FROM wp_posts
  WHERE (wp_posts.ID IN (SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (74) ) ) 
AND (wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish')  
) AS foo
WHERE rownumber <= 100
) 
)

)