带有多个AND的MySQL查询

时间:2011-11-25 22:02:01

标签: php mysql wordpress where

我是MySQL的新手,我遇到了使用PHP的查询问题。见最后三行。

$query = "
SELECT post_content, slug, ID
FROM wp_posts

INNER JOIN wp_term_relationships
ON wp_posts.ID = wp_term_relationships.object_id

INNER JOIN wp_terms
ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id

INNER JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id

WHERE post_status = 'publish' AND slug = 'a-slug' AND meta_key <> 'include' AND meta_key <> 'exkludera'
OR post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'include' AND meta_value = '72'
OR post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'exclude' AND meta_value <> '72'
";

我想说的最后三行:

第1行)选择查询是否: 是发布,有一个slu-and并没有meta_key“包含”或“排除”

第2行)选择查询是否: 是发布,有a-slug,有meta_key“include”,meta_value是'72'

第3行)选择查询是否: 是发布,有a-slug,有meta_key“排除”和meta_value不是'72'

但它给了我每个选择的双重或三重。 只有在匹配这三种情况中的一种时才应选择它。我做错了什么?

3 个答案:

答案 0 :(得分:4)

您需要使用括号:

WHERE (post_status = 'publish' AND slug = 'a-slug' AND meta_key <> 'include' AND meta_key <> 'exkludera')
OR (post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'include' AND meta_value = '72')
OR (post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'exclude' AND meta_value <> '72')

ORAND语句与您在示例中所做的混合评估为true post_status = 'publish'的所有情况。

顺便说一句,我假设Row 1)等引用代码中的行,而不是你想从数据库返回的行......

答案 1 :(得分:1)

将括号括在不同的标准集中应该会有所帮助。

e.g。

$query = "
...
WHERE 
(post_status = 'publish' AND slug = 'a-slug' AND meta_key <> 'include' AND meta_key <> 'exkludera')
OR 
(post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'include' AND meta_value = '72')
OR 
(post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'exclude' AND meta_value <> '72')
";

事实上,由于某些标准很常见,您可以像这样重写:

$query = "
...
WHERE 
post_status = 'publish' AND slug = 'a-slug' AND
(
 (meta_key <> 'include' AND meta_key <> 'exkludera')
 OR 
 (meta_key = 'include' AND meta_value = '72')
 OR 
 (meta_key = 'exclude' AND meta_value <> '72')
)
";

您还可以使用DISTINCT确保在必要时仅返回每条记录的一个副本。

SELECT DISTINCT post_content, slug, ID

答案 2 :(得分:0)

我有同样的问题。

我认为问题在于,在将OR与您正在使用的AND组合时,您不会包装OR。当一起使用OR和AND时,它们必须用parens&#34;()&#34;或者你会发生冲突。

这是一个链接,显示了如何工作的示例和写得很好的描述: http://www.w3schools.com/sql/sql_and_or.asp