Search code examples
mysqlsqlunselect

MYSQL unselect query from second table


Hi I have this two table

table 1

id    Selection  
-------------------
1     John           
2     Ely               
3     Marcus            
4     Steve           
5     Fritz           
6     Orly           
7     Carlo              
8     Lee    

table 2

id    Selected 
-------------------
1     John                         
3     Marcus 
4     Steve                     
5     Fritz           
7     Carlo 

the return would be the unselected rows. What would be the query for this output

id    Selection 
-------------------         
2     Ely                         
6     Orly                  
8     Lee

Solution

  • Use LEFT JOIN to join both table and t2.ID IS NULL to remove common records

    SELECT t1.* FROM table1 t1 
      LEFT JOIN table2 t2 
        ON t1.ID = t2.ID 
     WHERE t2.ID IS NULL
    

    Output:

    ╔════╦═══════════╗
    ║ ID ║ SELECTION ║
    ╠════╬═══════════╣
    ║  2 ║ Ely       ║
    ║  6 ║ Orly      ║
    ║  8 ║ Lee       ║
    ╚════╩═══════════╝
    

    See this SQLFiddle