内部JOIN缺少行

时间:2013-02-27 16:06:23

标签: mysql wordpress inner-join

首先我想提一下,在MYSQL和JOIN方面,我的技能有限。然而,这就是我拥有的和我想要实现的目标:

我有默认的WordPress表,喜欢从某个元键获取post_name,title,status和meta_value的结果。

这就是我所拥有的:

SELECT
    wp_posts.ID, wp_posts.post_name, wp_posts.post_title, wp_posts.post_status, wp_postmeta.meta_value
FROM wp_posts
INNER JOIN
    wp_term_relationships ON ( wp_posts.ID = wp_term_relationships.object_id ) 
INNER JOIN
    wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) 
WHERE (
        wp_term_relationships.term_taxonomy_id
        IN ( 1, 2, 3 )
    )
    AND wp_posts.post_type =  'my_post_type'
    AND (
        wp_posts.post_status
    IN (
        'my_status_1',  'my_status_2'
    )
)
AND wp_postmeta.meta_key =  'my_meta_key'
GROUP BY wp_posts.ID
ORDER BY wp_posts.ID ASC

当每个帖子都有'my_meta_key'的帖子时,一切都按预期工作。但如果缺少'my_meta_key',则帖子不在结果中。

我猜它是由第二次INNER JOIN引起的,但如上所述,我不知道应该用它替换它。

我确定这很简单

3 个答案:

答案 0 :(得分:1)

AND wp_postmeta.meta_key = 'my_meta_key'移至

INNER JOIN
    wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) 

像这样并改变INNER的LEFT

    LEFT JOIN
        wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id 
        AND wp_postmeta.meta_key =  'my_meta_key') 

如果你把条件放在" Where Clause"左连接将被"覆盖"。 我会添加一个建议。当你真的不需要它时,不要使用括号来保持你的代码易于阅读。

答案 1 :(得分:0)

INNER JOIN表格上的wp_postmeta更改为LEFT JOIN

LEFT JOIN wp_postmeta 
    ON ( wp_posts.ID = wp_postmeta.post_id ) 

WHERE的{​​{1}}过滤器移至wp_postmeta条件。

所以你的查询将是:

JOIN

SELECT wp_posts.ID, wp_posts.post_name, wp_posts.post_title, wp_posts.post_status, wp_postmeta.meta_value FROM wp_posts INNER JOIN wp_term_relationships ON ( wp_posts.ID = wp_term_relationships.object_id ) LEFT JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) AND wp_postmeta.meta_key = 'my_meta_key' WHERE wp_term_relationships.term_taxonomy_id IN ( 1, 2, 3 ) AND wp_posts.post_type = 'my_post_type' AND wp_posts.post_status IN ('my_status_1', 'my_status_2') GROUP BY wp_posts.ID ORDER BY wp_posts.ID ASC 语法只返回两个表中匹配的行。因此,如果您没有匹配的行,则不会得到任何结果。通过将其更改为INNER JOIN,即使LEFT JOIN表中没有匹配的行,也会返回所有行。如果该行不存在,则wp_postmeta表中的值将为wp_postmeta

答案 2 :(得分:0)

以下内容返回

  • 来自WP_Posts的所有记录
  • 仅限具有WP_TERM_RELATIONSHIPS
  • 的记录
  • 仅wp_postmeta中wp_posts中匹配记录的那些记录。

*

SELECT wp_posts.ID, wp_posts.post_name, wp_posts.post_title, 
  wp_posts.post_status, wp_postmeta.meta_value
FROM wp_posts
LEFT JOIN wp_term_relationships 
  ON wp_posts.ID = wp_term_relationships.object_id
LEFT JOIN wp_postmeta 
  ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_term_relationships.term_taxonomy_id IN ( 1, 2, 3 )
  AND wp_posts.post_type =  'my_post_type'
  AND wp_posts.post_statusIN ('my_status_1',  'my_status_2') 
  AND (wp_postmeta.meta_key =  'my_meta_key' or wp_postmeta.meta_key is null)
GROUP BY wp_posts.ID
ORDER BY wp_posts.ID ASC

你需要为null,否则wp_posts中没有wp_postmeta数据的记录将被排除。