2012-07-17 68 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

相關問題