MySQL在Wordpress数据库上需要连接

时间:2014-01-02 14:27:21

标签: mysql wordpress left-join

我是MySQL新手,最后在标准的Wordpress数据库上发表了这个声明,以获取最新文章。 但是,下面的语句要求在[wp_postmeta]中找到相关的行以获取属于文章的缩略图。 但是,有些帖子可能没有缩略图,但我仍然想要选择它们。

如何在[wp_postmeta]中将语句更改为不需要缩略图值?我相信我需要一个left join条款,但不知道该怎么做。

SELECT p.*, ( SELECT guid FROM wp_posts WHERE id = m.meta_value ) AS imgurl 
FROM wp_posts p, wp_postmeta m
WHERE p.post_type =  'post'
AND p.post_status =  'publish'
AND p.id = m.post_id
AND m.meta_key =  '_thumbnail_id'
ORDER BY post_date DESC

2 个答案:

答案 0 :(得分:1)

尝试使用加入和ON(p.id = m.post_id AND m.meta_key = '_thumbnail_id' )

SELECT DISTINCT p.*, ( SELECT guid FROM wp_posts WHERE id = m.meta_value LIMIT 1) AS imgurl 
FROM wp_posts p
LEFT JOIN  wp_postmeta m ON(p.id = m.post_id AND m.meta_key =  '_thumbnail_id' )
WHERE p.post_type =  'post'
AND p.post_status =  'publish'
ORDER BY post_date DESC

答案 1 :(得分:0)

使用此查询,它将获取最新的5个帖子,您可以增加显示限制。

 $sql = " SELECT * FROM wp_posts p
WHERE p.post_type =  'post'
AND p.post_status =  'publish'
AND p.post_type = 'post'
ORDER BY p.post_date DESC
LIMIT 5";