SQL在多行上选择条件数据

时间:2012-07-25 10:44:26

标签: mysql sql sql-server tsql


假设我有一个名为“tblTemp”的表,其中包含以下数据

ID        Name  
1           A  
2           B  
3           C  
4           A  
4           B  
5           A  
5           B  
5           C  
6           C  
6           B

我想从A& B的名字中获取ID而不是A& B& C,如下所示:

4          A 

4          B

我怎么能在sql中这样做?

我尝试以下sql但它也返回第5行:

SELECT     tblTemp.ID, tblTemp.Name
FROM         tblTemp INNER JOIN
                  tblTemp AS tbltemp_1 ON tblTemp.ID = tbltemp_1.ID
WHERE     (tblTemp.Name = 'A') AND (tbltemp_1.Name = 'B')

5 个答案:

答案 0 :(得分:2)

比较集合的方法之一是按照搜索集计算组计数,筛选组,并查看每个组的匹配数是否等于组成员的原始数量:

select tblTemp.ID
  from tblTemp
 inner join
 (
   select ID,
          count(*) GroupCount
     from tblTemp
    group by ID
   having count(*) = 2
 ) g
   on tblTemp.ID = g.ID
 where tblTemp.Name in ('A', 'B')
 group by tblTemp.Id, g.GroupCount
having count (*) = g.GroupCount

这应该适用于MySql和Sql Server。

You can play with this code @ Sql Fiddle

答案 1 :(得分:0)

您是否只想要一个包含A或B而不是C?

的不同ID列表
SELECT distinct ID
FROM tblTemp
WHERE Name = 'A' or Name = 'B'

EXCEPT

SELECT distinct ID
FROM tblTemp
WHERE Name = 'C'

我的上述解决方案适用于'A'和/或'B',但我注意到你实际上想要'A'和'B'没有或'。在那种情况下:

SELECT distinct ID
FROM tblTemp as T1
INNER JOIN tblTemp as T2
ON T1.ID = T2.ID
WHERE T1.Name = 'A' and T2.Name = 'B'

EXCEPT

SELECT distinct ID
FROM tblTemp
WHERE Name = 'C'

这是原始代码的扩展,可能不如@Madhivanan的解决方案那么优雅,但是如果A B和C更改为单词,则更为通用。

答案 2 :(得分:0)

尝试:

SELECT distinct ID
FROM tblTemp a
     LEFT JOIN tblTemp b
           ON a.ID = b.ID AND 
              b.name  = 'C'
WHERE b.ID IS NULL;

答案 3 :(得分:0)

select id from table
group by id
having min(Name)='A' and max(Nmae)='B'

答案 4 :(得分:0)

 SELECT ID, Name FROM tblTemp WHERE (Name = 'A' OR Name = 'B') and ID not in(SELECT ID FROM tblTemp WHERE Name = 'C')