sql示例:同一个表有teach_id和student_id,求同时学过这几个teach课程的学生;
select * from table_xxx where teach_id in (1,2,3) group by student_id having count(student_id ) = 3;
原理:先查出 teach_id 满足 in(1,2,3) 的条件,然后以student_id 分组,如果某个student_id 又count到相同个数(3个)那就正好是同时学过这几个teach课程的学生
注意:可能出现问题:
sql报错:xxx which is not functionally dependent on columns in GROUP BY clause
什么叫发生碰撞?比如我这里查出来的teach_id 有三个值,分别是1、2、3,这就是碰撞,因为聚合之后某一列有了多个值。
解决:
一、不select * 这里我们只需要同时学过这几个teach课程的:student_id就可以,那么改成:
select student_id from table_xxx where teach_id in (1,2,3) group by student_id having count(student_id ) = 3;
二、为查找出的发生碰撞的字段加上any_value函数,(不推荐:因为实际这个字段也变成了无效的,还不如不要)
三、关闭ONLY_FULL_GROUP_BY模式,这个模式,是mysql提供的安全检查,方案自行搜索,(视情况选择:应该很多人会嫌麻烦,或者数据库设置不让动)
附:如果你是使用mybatis,那么查询条件我给你写好了:mybatis:对一个字段多条件查询,取交集(对A字段匹配的多个B字段求交集)_caozg0的博客-CSDN博客