SQL查询where子句

时间:2012-04-23 15:24:47

标签: 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)

然后它得到了我想要的结果,但这是写这个的最好方法吗?我只是不想让这个代码遇到任何问题。

6 个答案:

答案 0 :(得分:8)

您需要在整个()子句中再添加一组AND。这表明client = $id必须为真,其他条件中的任何一个也必须为真= isinvoiced = 0isinvoiced = 1 and isrecurring = 1的组合。

 WHERE client = $id
    AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))

答案 1 :(得分:2)

AND子句周围添加一个括号:

WHERE client = $id
    AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))

答案 2 :(得分:1)

where client = $id
    and (
        isinvoiced = 0
        or (
            isinvoiced = 1
            and isrecurring = 1
            )
        )

答案 3 :(得分:1)

你想要的是这个:

WHERE client = $id AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))

如果您没有添加额外的blaquets,它将使OR与客户端重新生成并提供更多结果。

答案 4 :(得分:0)

关于SQL,您的目标应该是在conjunctive normal form(“AND条款的一系列”)中编写搜索条件。有各种rewrite rules可以帮助解决这个问题。

distributive rewrite law在这种情况下很有用,即

( P AND Q ) OR R   <=>   ( P OR R ) AND ( Q OR R )    

在你的情况下:

( isinvoiced = 0 ) OR ( isinvoiced = 1 AND isrecurring = 1 )

可以改写为:

( isinvoiced = 0 OR isinvoiced = 1 ) AND ( isinvoiced = 0 OR isrecurring = 1 )

因此,整个搜索条件没有笨拙的parens:

....
WHERE client = $id
      AND ( isinvoiced = 0 OR isinvoiced = 1 ) 
      AND ( isinvoiced = 0 OR isrecurring = 1 );

答案 5 :(得分:-1)

如果删除了初始where子句

remove -> WHERE client = $id

并且只是

 WHERE (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1 and client = $id)

这能让你得到你想要的结果吗?