4

我有一张桌子

ID NAME
--------
1  AAA
2  BBB
2  AAA
2  CCC
1  DDD
2  DDD

我必须显示与 ID 1 和 2 链接的记录

NAME
----
AAA
DDD

我正在使用以下查询 -

Select Name from table1 where ID IN (1,2);

但它向我展示了-

NAME
-----
AAA
BBB
CCC
DDD

如何更改查询以解决此问题?

4

5 回答 5

6
SELECT DISTINCT NAME
FROM tabel1 t1
join table1 t2
on t1.id = 1 and t2.id = 2 and t1.name = t2.name

或者如果可以有很多匹配项

SELECT DISTINCT NAME
FROM tabel1 t1
WHERE EXISTS (SELECT 1 FROM table1 t2 WHERE t1.name = t2.name and t2.id = 2)
and t1.id = 1

或者

SELECT NAME FROM tabel1 WHERE id = 1
INTERSECT
SELECT NAME FROM tabel1 WHERE id = 2
于 2013-07-26T11:50:34.287 回答
2

您需要按名称进行分组,然后计算您希望过滤的不同 ID。

select name
from table
where id in (1,2)
group by name
having count (distinct ID) = 2
于 2013-07-26T11:49:04.410 回答
1
Select Name 
from table1 
where ID IN (1,2)
and Name in  ( select Name               
                 from table1 
                where ID IN (1,2)
               group by Name
               having count(id) =2 
             ) ;
于 2013-07-26T11:46:31.040 回答
1
Select Name from TableName 
where id in (1,2)
 group by Name having Count(Distinct Id)>1
于 2013-07-26T11:49:19.123 回答
1
select name 
from table t
where id = 1 and exists 
(select 1 from table where name = t.name and id = 2)
于 2013-07-26T11:51:40.953 回答