SQL查询where子句
我的sql查询中有以下行:SQL查询where子句,sql,where-clause,Sql,Where Clause,我的sql查询中有以下行: WHERE client = $id AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1) 结果比我预期的要多。但是,如果我这样写: WHERE client = $id AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1 and client = $id) 然后我得到了我想要的结果,但这是写这篇文章的最好方式吗?
WHERE client = $id
AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1)
结果比我预期的要多。但是,如果我这样写:
WHERE client = $id
AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1 and client = $id)
然后我得到了我想要的结果,但这是写这篇文章的最好方式吗?我只是不想在这段代码中再遇到任何问题 在整个
和子句周围还需要一组()
。这表明client=$id
必须为true,并且其他条件中的任何一个也必须为me true=isinvoice=0
或isinvoice=1和isrecurring=1的组合
WHERE client = $id
AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))
如果删除首字母where子句
remove -> WHERE client = $id
只要有
WHERE (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1 and client = $id)
这会得到您想要的结果吗?在您的和子句周围添加一个括号:
WHERE client = $id
AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))
你想要的是:
WHERE client = $id AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))
如果您不放置额外的blaques,它将使用客户端restiction生成一个或,并提供更多结果。关于SQL,您应该将搜索条件写入(“一系列和
子句”)。在这方面有各种各样的帮助
在这种情况下,即
( P AND Q ) OR R <=> ( P OR R ) AND ( Q OR R )
可改写为:
( isinvoiced = 0 OR isinvoiced = 1 ) AND ( isinvoiced = 0 OR isrecurring = 1 )
因此,整个搜索条件没有笨拙的参数:
....
WHERE client = $id
AND ( isinvoiced = 0 OR isinvoiced = 1 )
AND ( isinvoiced = 0 OR isrecurring = 1 );
完美的Michael,这正是我想要的,再次感谢……我会在你的答案允许的时候投票支持你的答案。如果isinvoiced=1
与isinvoiced=0
正好相反(即isinvoiced
不能包含任何其他值,也不能NULL
),你可以进一步简化它:WHERE client=$id和(isinvoiced=0或isrecurring=1)
.Google for。你确定你理解a和b或c
与a和(b或c)
之间的区别吗?你的例子写得更清楚,不是你真正想要的。OP希望始终在客户端上匹配。请参阅接受的答案。
( isinvoiced = 0 OR isinvoiced = 1 ) AND ( isinvoiced = 0 OR isrecurring = 1 )
....
WHERE client = $id
AND ( isinvoiced = 0 OR isinvoiced = 1 )
AND ( isinvoiced = 0 OR isrecurring = 1 );