2010-06-27 89 views
0

我想查詢以獲得帖子的標題,鏈接和圖像。我有什麼,我需要用下面的查詢:wordpress mysql查詢發佈縮略圖

SELECT WPPOSTS.post_title,WPPOSTS.guid,WPPOSTS_2.image 
FROM wp_posts WPPOSTS 
LEFT JOIN 
( 
SELECT guid AS image,post_parent 
FROM wp_posts 
WHERE post_type = 'attachment' 
ORDER BY post_date_gmt DESC 
) WPPOSTS_2 ON (WPPOSTS_2.post_parent = WPPOSTS.ID) 
WHERE WPPOSTS.ID IN (2439,2395,2355) 

現在,我真正想要的是讓只有在插入後最後一個縮略圖,不是所有的人。這就是爲什麼我已經考慮過訂購條款的原因。我試圖在左加入選擇內部放置一個「限制1」,但我想這是錯誤的。

有什麼想法?謝謝

回答

1

您不希望在您的嵌套選擇上設置LIMIT,因爲它只會找到1行 - 對於您想要的每篇文章而言不是一行。

您可以使用嵌套select來爲每個帖子查找MAX(post_date_gmt)(我認爲您希望GROUP BY post_parent?),然後爲匹配最高發布日期的圖像選擇guid。

嘗試類似如下(我沒有測試過這一點,所以把它當作一粒鹽):

SELECT a.post_title,max(c.guid) 
FROM wp_posts a 

LEFT JOIN 
(select post_parent, max(post_date_gmt) as latest_image_date from wp_posts 
where post_type='attachment' GROUP BY post_parent) b 
on a.id=b.post_parent 

LEFT JOIN wp_posts c 
on c.post_parent=a.id 
and c.post_type='attachment' 
and b.latest_image_date = c.post_date_gmt 

GROUP BY a.post_title 

MAX對GUID的每個職位最終選擇只是試圖保證在不太可能的情況下,在單個帖子中有多個圖像具有完全相同的時間戳。

3

我發佈我的解決方案,因爲這也可以幫助其他人。由於上面的代碼工作,但也打印最大(c.guid)NULL元素,我篩選這些結果。除了這一點,更容易得到的結果,如果關聯數組返回得到很好的名字:

SELECT a.post_title title, max(c.guid) img_url, a.ID id 
FROM wp_posts a 

LEFT JOIN 
(select post_parent, max(post_date_gmt) as latest_image_date from wp_posts 
where post_type='attachment' GROUP BY post_parent) b 
on a.id=b.post_parent 

LEFT JOIN wp_posts c 
on c.post_parent=a.id 
and c.post_type='attachment' 
and b.latest_image_date = c.post_date_gmt where c.guid IS NOT NULL 

GROUP BY a.post_title ORDER BY a.ID 

一個mysql_fetch_array()可能是這樣的:

title img_url  id 
Despre http://localhost/drumliber/wp-content/uploads/2009... 2 
Brandul de tara al Romaniei - imnul turistic http://localhost/drumliber/wp-content/uploads/2009... 9