where条件多列上的多个值

时间:2014-08-04 14:46:47

标签: sql sql-server-2008

create table testCondition(obj int, prop int, val nvarchar(255));
Go
insert into testCondition values(1, 10, 'A')
insert into testCondition values(1, 11, 'B')
insert into testCondition values(1, 12, 'C')
insert into testCondition values(2, 10, 'E')
insert into testCondition values(2, 11, 'B')
insert into testCondition values(2, 12, 'C')

此表包含2M +这样的记录。 如何列出所有对象(prop = 10和val =' A')和(prop = 12和val =' C')?

预期产出:

1, 10, 'A'
1, 12, 'C'

2 个答案:

答案 0 :(得分:1)

使用OR

...
WHERE (prop = 10 and val = 'A')
  OR  (prop = 12 and val = 'C')

编辑:现在我明白了,您希望两个条件都为真的给定ID的所有行。这也是您省略2, 12, 'C'的原因,因为2没有prop = 10 and val = 'A'行。

然后我会使用EXISTS

SELECT * FROM testCondition tc
WHERE (
  prop = 10 and val = 'A'
  AND EXISTS
  (
      SELECT 1 FROM testCondition tc2
      WHERE tc2.obj = tc.obj AND prop = 12 AND val = 'C'
  )
)
OR (
  prop = 12 and val = 'C'
  AND EXISTS
  (
      SELECT 1 FROM testCondition tc2
      WHERE tc2.obj = tc.obj AND prop = 10 AND val = 'A'
  )
)

这是一个演示:http://sqlfiddle.com/#!3/8fe0c/2/0

答案 1 :(得分:0)

这应该可以解决问题:

SELECT 
    a.obj, a.prop, a.val 
FROM
    testCondition a
    JOIN (SELECT obj FROM testCondition WHERE (prop = 10 AND val = 'A')) AS b ON a.obj = b.obj
    JOIN (SELECT obj FROM testCondition WHERE (prop = 12 AND val = 'C')) AS c ON a.obj = c.obj
WHERE 
  ((prop = 10 AND val = 'A') OR 
  (prop = 12 AND val = 'C'))

两个JOINS确保我们只抓取两个条件都为真的obj-id。然后,我们使用WHERE子句中的有效obj id过滤掉不需要的行。

Here's an example sqlfiddle.