查找查找帖子没有自定义字段

时间:2013-04-07 05:35:42

标签: sql wordpress

我编写此查询以查找具有自定义字段“语言”的帖子,其值为“英语”或帖子根本没有自定义字段“语言”。

SELECT DISTINCT wp_posts.* FROM wp_posts, wp_postmeta 
WHERE wp_posts.ID = wp_postmeta.post_id  
AND (wp_postmeta.meta_key = 'language' AND wp_postmeta.meta_value like '%English%' OR NOT EXISTS (SELECT * FROM wp_posts, wp_postmeta Where wp_postmeta.meta_key = 'language' ))

但是,它仅返回具有自定义字段“language”的帖子,其值为“English”

请帮帮我

2 个答案:

答案 0 :(得分:1)

你应该注意条件 -

中的括号

尝试以下查询 -

SELECT DISTINCT wp_posts.* FROM wp_posts , wp_postmeta 
WHERE wp_posts.ID = wp_postmeta.post_id  
AND ((wp_postmeta.meta_key = 'language' AND wp_postmeta.meta_value like '%English%' ) OR NOT EXISTS (SELECT * FROM wp_posts, wp_postmeta Where wp_postmeta.meta_key = 'language' ))

还有一件事你需要对现有子查询中的ID有一个条件,如下所示 -

SELECT DISTINCT wp_posts.* FROM wp_posts , wp_postmeta 
    WHERE wp_posts.ID = wp_postmeta.post_id  
    AND ((wp_postmeta.meta_key = 'language' AND wp_postmeta.meta_value like '%English%' ) OR NOT EXISTS (SELECT 1 FROM wp_postmeta wp_postmeta1 Where wp_postmeta1.meta_key = 'language' and wp_postmeta1.post_id = wp_postmeta.post_id ))

答案 1 :(得分:0)

试试这个,

SELECT DISTINCT wp_posts.* FROM wp_posts, wp_postmeta 
WHERE wp_posts.ID = wp_postmeta.post_id  
AND (wp_postmeta.meta_key = 'language' AND 
     wp_postmeta.meta_value like '%English%')
OR (wp_postmeta.meta_key != 'language');  --Not sure if you want (!= language) or null. Change as required.