wordpress mysql查询帖子缩略图

wordpress mysql查询帖子缩略图,mysql,wordpress,Mysql,Wordpress,我试图做一个查询,以获得文章的标题,链接和图片的文章。我有以下查询所需的内容: 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 O

我试图做一个查询,以获得文章的标题,链接和图片的文章。我有以下查询所需的内容:

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”,但我想这是错误的


有什么想法吗?谢谢

您不想对嵌套的select设置限制,因为它只会找到一行,而不是像您希望的那样为每个帖子找到一行

您可以使用嵌套的select查找每篇文章的最大值(post_date_gmt)(我想您可能希望按post_parent?进行分组),然后为与最高发布日期匹配的图像选择guid

试试下面的方法(我还没有测试过,所以要小心):


最后为每篇文章在guid上选择MAX只是为了在一个不太可能的情况下保证唯一性,即在一篇文章上有多个具有完全相同时间戳的图像。

您不想对嵌套的select设置限制,因为它只会找到一行,而不是像您所希望的那样为每篇文章找到一行

您可以使用嵌套的select查找每篇文章的最大值(post_date_gmt)(我想您可能希望按post_parent?进行分组),然后为与最高发布日期匹配的图像选择guid

试试下面的方法(我还没有测试过,所以要小心):


最后在每个帖子的guid上选择MAX只是为了在一个帖子上有多个具有完全相同时间戳的图像的情况下保证唯一性。

我发布我的解决方案,因为这可能也会帮助其他人。因为上面的代码可以工作,但也为max(c.guid)打印空元素,所以我过滤这些结果。除此之外,如果返回的关联数组具有良好的名称,则更容易获得结果:

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

我发布我的解决方案,因为这可能也会帮助其他人。因为上面的代码可以工作,但也为max(c.guid)打印空元素,所以我过滤这些结果。除此之外,如果返回的关联数组具有良好的名称,则更容易获得结果:

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