2012-07-17 66 views
0

我有一个查询返回与给定criteia匹配的数据库表中的所有帖子,但我正在寻找一种方法,最多只能返回5个帖子每个'post_type'。目前查询是选择每一个匹配的文章,我不得不限制每个'post_type'在PHP中的数字,这不是特别有效。在数据库表中返回每个'post_type'的最多5个

可以这样做吗?谢谢。

SELECT ID, post_title, post_type 
FROM wp_posts 
WHERE 1=1 
AND post_status = "publish" 
AND (
    post_type IN (
     "staff" 
    ) 
    AND post_name LIKE "%The%" 
) 
OR (
    post_type NOT IN (
     "staff", 
     "Attachment" 
    ) 
    AND (
     post_name LIKE "%The%" 
     OR post_title LIKE "%The%" 
    ) 
) 
ORDER BY post_type, post_name ASC 
+0

?最近的五个?最早的五个?你可以请张贴你的模式吗? – 2012-07-17 10:06:17

回答

1

该解决方案将选择每个post_type最近五次(基于id)职位:

SELECT  a.id, a.post_title, a.post_type 
FROM  wp_posts a 
INNER JOIN wp_posts b ON a.post_type = b.post_type AND a.id <= b.id 
WHERE  a.post_status = 'publish' AND 
      (a.post_type = 'staff' AND a.post_name LIKE '%The%') OR 
      (a.post_type NOT IN ('staff', 'Attachment') AND (a.post_name LIKE '%The%' OR a.post_title LIKE '%The%')) 
GROUP BY a.id, a.post_title, a.post_type 
ORDER BY a.post_type, a.post_name 
HAVING  COUNT(1) <= 5 
你要为每种类型的哪些职位
+0

非常感谢您的回复。我试过这个,但是在'HAVING COUNT(1)<= 5'上出现语法错误。按照预期的结果给出结果(尽管所有这些结果都不是每个结果中的5个结果)。我错过了什么吗?谢谢。 – 2012-07-17 10:57:51

相关问题