2010-06-27 47 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