采用连接字符串比较结果集是否相同,group

mac2025-10-27  4

查询与学号为"01"的同学所学课程相同的同学的信息

在参考博客文章中, 13、查询和"01"号的同学学习的课程完全相同的其他同学的信息。 给出的参考答案是:

select Student.* from Student where SID in (select distinct SC.SID from SC where SID <>01and SC.CID in (select distinct CID from SC where SID =01) group by SC.SID having count(1) = (select count(1) from SC where SID=01))

我们可以看出,这个查询结果是正确的

但是更新为和‘06’号同学比较,就会发现查询结果不对,因为这个是比较查询返回的数量相同,而不是查询结果内容相同

百度这个问题,在这篇博客,可点击查看,解决办法是

select * from student where sid in (select sid from grade2 where sid not in (select sid from grade2 where cid not in (select cid from grade2 where sid='01')) group by sid having count(*)=(select count(*) from grade2 where sid='01') and sid != '01');

第一眼看上去还是在比较查询结果数量,而且看上去嵌套很多很复杂。也可以研究下他的思路。

我就问我的研发老公,他说拼接字符串很简单,让我自己查,于是找到了函数group_concat(),这个函数可以将查询结果集拼接成字符串,然后进行比较。

select a.* from student a,sc b where a.sid=b.sid and a.sid <>'06' group by a.sid having group_concat(b.cid)= (select group_concat(b.cid) from student a,sc b where a.sid=b.sid and a.sid ='06' order by cid desc)

就这样问题就解决了,不明白group by 和having用法的话,可参考我的另一篇博客。

如有错误,可以在下方评论联系我,谢谢!

最新回复(0)