MYSQL从第二个表中选择查询

时间:2013-07-18 06:56:05

标签: mysql sql unselect

嗨,我有这两张桌子

表1

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

表2

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

返回将是未选择的行。这个输出的查询是什么

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

3 个答案:

答案 0 :(得分:2)

使用LEFT JOIN加入表格和t2.ID IS NULL以删除常用记录

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

输出:

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

请参阅this SQLFiddle

答案 1 :(得分:1)

您可以使用Left Join

 Select t1.id,t2.selection from 
 table1 t1 left join table2 t2 
 ON t1.ID = t2.ID 
 where t2.id is null;

答案 2 :(得分:0)

使用此查询。它为你工作。

select table1.* from table1 where table1.id not in (select id from table2)