用于查找id的SQL查询,其中field1 = x,field1 = y

时间:2011-02-28 02:00:05

标签: sql sql-server tsql sql-server-2008

我有这张桌子(简化)

 ID  | Field1
---------------------------------
 2   | Cat     
 2   | Goat
 6   | Cat
 6   | Dog 

我需要找到存在记录的ID,其中field1的值为cat,对于相同的id,存在另一个值为Goat的记录。在这种情况下,它只会返回ID 2。

执行以下操作无效。     其中Field1 ='Cat',Field1 ='Goat'

我猜这里需要某种子查询?我不完全确定。 (使用SQL Server 2008)

5 个答案:

答案 0 :(得分:2)

使用:

  SELECT t.id
    FROM YOUR_TABLE t
   WHERE t.field1 IN ('Cat', 'Goat')
GROUP BY t.id
  HAVING COUNT(DISTINCT t.field1) = 2

此处的关键是使用COUNT(DISTINCT ...)来获取field1值的计数。如果用户有Cat 3x和狗1x并不重要......除非你需要过滤掉那些?

另一个选项是INTERSECT, which returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand

SELECT a.id 
  FROM YOUR_TABLE a 
 WHERE a.field1 = 'Cat'
INTERSECT
SELECT b.id 
  FROM YOUR_TABLE b 
 WHERE b.field1 = 'Goat'

答案 1 :(得分:2)

试试这个:

SELECT id FROM
(
 SELECT id FROM <YOUR_TABLE> WHERE Field1 = 'Cat'
 INTERSECT
 SELECT id FROM <YOUR_TABLE> WHERE Field1 = 'Goat'
) a

替代:

SELECT a.ID 
  FROM <YOUR_TABLE> a INNER JOIN <YOUR_TABLE> b 
    ON a.ID = b.ID
WHERE a.Field1 = 'CAT'
  AND b.Field1 = 'GOAT'

答案 2 :(得分:0)

未经测试,但此类内容可能有效

select t1.ID from tbl t1 inner join tbl t2 on t1.ID=t2.ID
where (t1.Field1='Cat' and t2.Field1='Goat')

答案 3 :(得分:0)

使用像这样的查询

SELECT ID FROM table INNER JOIN 
    (SELECT ID, COUNT(FILED1) AS Expr1 
       FROM table GROUP BY ID 
          HAVING COUNT(FIELD1) > 1) SR ON table.ID = SR.ID  WHERE table.FIELD1 = 'Cat'

如果你想要一个更动态的查询,你只需要为'Cat'添加一个带有DECLARE的变量

答案 4 :(得分:0)

SELECT DISTINCT t1.ID 
FROM table t1, table t2
WHERE t1.ID=t2.ID AND t1.Field1 <> t2.Field1