我想找到最优化的方法从表中选择具有相同名称(如特定记录)的行。
ID NAME
10 A
10 C
10 B
20 A
30 D
31 B
然后选择:
ID NAME
20 A
31 B
我想到了这样的事情:
select * from table
where name in (select name from table where id = 10).
还有其他选择吗?
答案 0 :(得分:0)
select name
from table
group by name
having count(*) > 1
答案 1 :(得分:0)
我想你想要
select t.*
from t
where t.id <> 10 and
t.name in (select t2.name from t t2 where t2.id = 10);
哦,基本上就是您的查询。您也可以这样做:
select t.*
from (select t.*,
sum(case when id = 10 then 1 else 0 end) over (partition by name) as has_name_10
from t
) t
where has_name_10 = 1 and id <> 10;
答案 2 :(得分:0)
另一种方式:
with diff_name as (
select * from(
select 10 id , 'A' name from dual
union
select 10 id , 'B' name from dual
union
select 10 id , 'C' name from dual
union
select 20 id , 'A' name from dual
union
select 30 id , 'D' name from dual
union
select 31 id , 'B' name from dual))
select distinct b.* from diff_name a,
diff_name b
where a.name=b.name
and a.id <>b.id
and a.id = 10