现在有两个表
表1 有course_id和student
表2 也有course_id和student_id
如果在表1中的course_id和student_id在表2中出现表示已购买, 否则为 未购买。

现在我要获取表1 中未购买的数据~

我之前用的foreach表1的数据然后根据course_id和student_id去查询表2,如果存在说明已购买。但是这种方式会很慢,没遍历一次会查询一次表;

求大神指点更快的方法。(不修改表结构)

回复内容:

现在有两个表
表1 有course_id和student
表2 也有course_id和student_id
如果在表1中的course_id和student_id在表2中出现表示已购买, 否则为 未购买。

现在我要获取表1 中未购买的数据~

我之前用的foreach表1的数据然后根据course_id和student_id去查询表2,如果存在说明已购买。但是这种方式会很慢,没遍历一次会查询一次表;

求大神指点更快的方法。(不修改表结构)

感谢各位的意见。这样也可以~

select * from A where (course_id,student_id) not in (select course_id,student_id from B)
登录后复制

如果你用的是mysql或者oracle,用下面的语法:

SELECT course_id, student FROM table1
MINUS SELECT course_id, student from table2;
登录后复制

其他的把MINUS换成EXCEPT。

08-24 08:27