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

2025-02-02 18:00:32
推荐回答(4个)
回答1:

带有中国的所有记录(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='香港')

回答2:

--凑热闹的
--select 表A.* from 表A
join
(
select aid from 表B
where tagname = '中国' and tagname != '香港'
) temp_B
on 表A.id = temp_B.aid
--带有中国不带有香港,额,不是政治话题,但是表B中中国和香港是并列的记录啊,有中国肯定没香港了,真的不是政治话题···

回答3:

试试
select * from a where exists (select * from b where b.aid=a.id and b.tagname ='中国' and b.tagname<>'香港')

回答4:

select * from b where tagname ='中国' and aid not in (select aid from b where tagname ='香港')