我有一张桌子
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
如何更改查询以解决此问题?
答案 0 :(得分: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
答案 1 :(得分:2)
您需要按名称分组,然后计算您希望过滤的不同ID。
select name
from table
where id in (1,2)
group by name
having count (distinct ID) = 2
答案 2 :(得分: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
) ;
答案 3 :(得分:1)
Select Name from TableName
where id in (1,2)
group by Name having Count(Distinct Id)>1
答案 4 :(得分:1)
select name
from table t
where id = 1 and exists
(select 1 from table where name = t.name and id = 2)