SQL问题,两个表联合查询筛选条件的问题。

表A
id title content

1 标题1 内容
2 标题2 ……
3 标题3 ……
表B
aid tagid tagname
2 1 中国
1 2 美国
3 3 中国
3 4 香港

现使用 select a.* from a inner join b on a.id=b.aid where b.tagname='中国' and a.id not in (select aid from b where tagname='香港')

来选出tagname带有中国但不含有香港的A表数据

请问除了使用not in 还有其他更好的方法吗?

带有中国的所有记录(ID=3时,只显示是中国的一条):
select a.* from a inner join b on a.id=b.aid where b.tagname='中国'

只有有香港,所属ID全都不显示:
select a.* from a inner join b on a.id=b.aid where b.tagname='中国' and not exists(select 1 from b as c where c.id=a.id and tagname='香港')
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-27
--凑热闹的
--select 表A.* from 表A
join
(
select aid from 表B
where tagname = '中国' and tagname != '香港'
) temp_B
on 表A.id = temp_B.aid
--带有中国不带有香港,额,不是政治话题,但是表B中中国和香港是并列的记录啊,有中国肯定没香港了,真的不是政治话题···
第2个回答  2013-04-27
试试
select * from a where exists (select * from b where b.aid=a.id and b.tagname ='中国' and b.tagname<>'香港')
第3个回答  2013-04-27
select * from b where tagname ='中国' and aid not in (select aid from b where tagname ='香港')
相似回答