sql查找既有a又有b

mike089 2011-03-09 06:25:11
id type
1 a
1 b
1 c
1 d
2 a
3 g
4 b

sql查找既有a又有b的id

结果
1
...全文
2898 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
benluobobo123 2011-03-10
  • 打赏
  • 举报
回复
if object_id('A') is not null
drop table A

create table A(id int, type varchar(10))

insert into A
select 1 ,'a' union all
select 1 ,'b' union all
select 1 ,'c' union all
select 1 ,'d' union all
select 2 ,'a' union all
select 3 ,'g' union all
select 4 ,'b'

select id from A where type='a'
intersect
select id from A where type='b'
zhaozhen2004 2011-03-10
  • 打赏
  • 举报
回复 1
select id
from test
where type in ('a','b')
group by id
having count(id) > 1
zhaozhen2004 2011-03-10
  • 打赏
  • 举报
回复
select id
from test
where type = 'a' or type = 'b'
group by id
having count(id) > 1
叶子 2011-03-09
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 fcuandy 的回复:]
select id from tb where tpye in ('a','b') group by id having count(distinct type)=2
[/Quote]
+1
--小F-- 2011-03-09
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 fcuandy 的回复:]
select id from tb where tpye in ('a','b') group by id having count(distinct type)=2
[/Quote]
fcuandy 2011-03-09
  • 打赏
  • 举报
回复
如果是又有a,又有b,c,d,e... 要写5个join还是5个exists? hehe
gaogaohui8209 2011-03-09
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 acherat 的回复:]
SQL code

select id
from tb t
where [type] = 'a' and exists (select 1 from tb where id = t.id and [type] = 'b')
[/Quote]

up
AcHerat 2011-03-09
  • 打赏
  • 举报
回复

select id
from tb t
where [type] = 'a' and exists (select 1 from tb where id = t.id and [type] = 'b')
fcuandy 2011-03-09
  • 打赏
  • 举报
回复
select id from tb where tpye in ('a','b') group by id having count(distinct type)=2
javatemptation 2011-03-09
  • 打赏
  • 举报
回复

use tempdb;
/*
create table test
(
id int not null,
[type] varchar(5) not null
);
insert into test(id,[type])
values
(1,'a'),
(1,'b'),
(1,'c'),
(1,'d'),
(2,'a'),
(3,'g'),
(4,'b');
*/
select t1.id
from test as t1
join test as t2
on t1.id = t2.id
where t1.type = 'a'
and t2.type = 'b';
mike089 2011-03-09
  • 打赏
  • 举报
回复
还有更好的方法吗
快溜 2011-03-09
  • 打赏
  • 举报
回复
select a.id from
(select id from tb where type='a') a,
(select id from tb where type='b') b
where a.id=b.id

11,850

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 非技术版
社区管理员
  • 非技术版社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧