sql 多对多查询

表结构如图所示
aID和bID分别对应表a和表b的ID
现要求查询出同时具有q、r两个Job对应的Name
求sql代码怎么写
当然上文描述的只是简化情况,肯定会需要同时具有更多的Job,嵌套查询的话就不需要了。

select *
from
(select id,sum(money) as mm from a表 group by id) aaa,
(select id,sum(money) as nn from b表 group by id) bbb
where aaa.id=bbb.id and aaa.mm=bbb.nn;
-----------------------------
说明:
先用语句,得到aaa,bbb两个临时表,里面是(ID,钱的求和);
然后叠加一个查询,从表aaa,表bbb中,用条件,筛选出需要的记录(ID相等,钱求和相等);mm,nn是我为了字段查看方便,设置的两个临时字段名。
-----------------------------
如果你是用workbench,语句正确执行要写成一行。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-11-13
好几种写法,我这里就写一个算抛砖引玉吧,也算给你一个提示。
select name from a where id in (select c.aid from c where bin in (select id from b where job in ('q','r')))
也可以直接关联到c表然后相等,这个办法应该不错,可以直接对应。追问

同时!同时!同时!重要的事说三遍。
也就是查出来的name必须同时至少有q,r两个Job,
你这么写查出来的会带有只有q或只有r的Name

追答

怎么说呢,这个有点麻烦,本人oracle出身,如果你是其他数据库,那么仅供参考。
你用的不知道是什么数据库,如果是oracle那么一条语句执行多次,求交集(intersect)。
可以用循环搞定。
select name from a where id in (select c.aid from c where bin in (select id from b where job='q'))
intersect
select name from a where id in (select c.aid from c where bin in (select id from b where job='r'))
不过这个语句在其他数据库不知道有没有,如果条件多,那么就写多个。
另外一个我想了一下,需要一个字符串连接类似的聚合函数。oracle有wmsys.wm_concat,当然这个是不够的,还需要自己写这里要B表要的结果是%1%4%,然后D对C表查询,利用group by aid聚合,得到字符串聚合假设说124,那么124是不是like %1%4%,这个也就可以达到你的要求,数字好象没办法like吧。而且不是嵌套查询,不过这个函数只能自己写,不过网上有,你找到改改应该可以用,不过效率就不好说了。
不过这两种查询的效率,个人估计高不了。
也是个人感觉可能最快的。
还有一种,感觉上应该可以,不过只能给出大体的意思,毕竟很多内容没办法试验。
select aid from c where bin in (select id from b where job in ('q','r')) group by aid having sum(bid)=5;
那么这时的aid就是你要的结果。后面的sum(bid)=5,不知道5能不能用自查询
select sum(id) from b where job in ('q','r') 代替,如果可以,那么可能就能实现了。

本回答被提问者和网友采纳
第2个回答  2015-11-13
select name,job from 表a,表b where 表a.ID=表b.ID and (Job="q" or Job="r");
第3个回答  2014-03-17
select a.id from
(select id,sum(money) m from a group by id) a
left join
(select id,sum(money) m from b group by id) b
on (a.id=b.id and a.m=b.m)

这个你试试
第4个回答  2019-05-16
select a.Name,b.JOb from 表c c , 表b b , 表a a
where c.aID =a.ID
and c.bID =b.ID
and b.ID in('q','r')
相似回答