MySQL: difference of two result sets

后端 未结 3 867
暗喜
暗喜 2020-12-08 00:51

How can I get the set difference of two result sets?

Say I have a result set (just one column in each):

result1:
\'a\'
\'b\'
\'c\'

result2:
\'b\'
\'         


        
3条回答
  •  孤街浪徒
    2020-12-08 00:54

    I recently had this requirement where I had to find the difference between two resultsets. Although the above answers helped me wished they were a little detailed. For the given question I found two interpretation:

    1. The resultset could be from 2 different tables
    2. The resultset from the same table

    For the first one where the resultset can be from 2 different tables, let's take two tables: science_student and math_student.


    science_student


    math_student


    I want to calculate the difference between these 2 resultsets, that is:
    result1 - result2
    
    result1: select student_id from science_student where id > 2
    
    result2: select student_id from math_student
    

    The difference between result1 - result2 is STUD3

    So the query to find the difference will be:

    select result1.student_id 
     from 
     (select student_id from science_student where id > 2) result1
     left join
     (select student_id from math_student) result2
     on result1.student_id = result2.student_id 
     where result2.student_id is null;
    



    For the second interpretation where the resultset can be from the same table:

    result1 - result2
    
    result1: select student_id from science_student 
    
    result2: select student_id from science_student where id > 2
    

    The difference between result1 - result2 is STUD1, STUD2

    And the query for the same will be:

    select result1.student_id 
     from 
     (select student_id from science_student) result1
     left join
     (select student_id from science_student where id > 2) result2
     on result1.student_id = result2.student_id 
     where result2.student_id is null;
    

提交回复
热议问题