0

我有一个包含多个字段的表,我想选择两个字段等于某个值并且 field3 为 1 且 field4 为 4、5、6 或 field3 为 0 的所有行。但是当 field3 为 0 时我需要返回结果并且 field4 是 4、5、6。通过这个查询,我没有返回 field3 = 0 的行。

这是我的查询,

SELECT * from table where field1 = 1 AND field2 = 0 AND (field3 = 1 AND field4 !=4
AND field4 !=5
AND field4 !=6)
4

2 回答 2

2

尝试这样的事情:

SELECT * from table where 
          field1 = 1 AND field2 = 0 
            AND (
                  (field3 = 1 AND (field4 = 4 OR field4 = 5 OR field4 = 6))
                     OR 
                  (field3 = 0)
                )
于 2013-07-30T06:33:40.207 回答
1

完全根据你的散文文本对你的陈述进行聚类和括号,你就在那里。

SELECT *
FROM
    table
WHERE
    field1 = x
    AND field2 = y
    AND (
        (field3 = 1 AND field4 IN (4, 5, 6))      -- field3 = 1 and field4 has one of specified values
        OR                                        -- or alternatively
        (field3 = 0 AND field4 NOT IN (4, 5, 6))  -- field3 = 0 and field4 doesn't have any of the specified values
    )

编辑: 实际上 - 再次阅读您的帖子后,您希望 field4 为 4、5 或 6,并且您希望 field3 为 0 或 1 - 还是我错了?这意味着:

SELECT *
FROM
    table
WHERE
    field1 = x
    AND field2 = y
    AND field3 IN (0, 1)
    AND field4 IN (4, 5, 6))
于 2013-07-30T06:31:07.543 回答