2017-05-04 51 views
0

我有两个表:table1和table2都有一列的ID。我想在table1中创建一个列,如果table1中的ID位于table2中,则显示'Y';如果不是,则显示'N'。SQL CASE当在表中

目前,我使用:

Select id, case when id in (table2) then 'Y' else 'N' end as in_table2 
from table1 

然而,由于这两个表都非常大,查询永远走。有没有更有效的方法来做到这一点?

感谢

回答

1

使用exists

Select t1.id, 
     (case when exists (select 1 from table2 t2 where t2.id = t1.id) 
      then 'Y' else 'N' 
     end) as in_table2 
from table1 t1; 
0

这应该是比使用更快捷,高效的存在/子查询:

SELECT t1.id , 
      CASE WHEN t2.id IS NULL 
       THEN 'N' 
       ELSE 'Y' 
      END AS in_table2 
    FROM table1 t1 
      LEFT JOIN TABLE2 t2 ON t1.id = t2.id; 

通过左侧的接合部你保持对表2的记录知名度,如果ID为空,你知道它存在于table1上,但不在table2上,所以你可以安全地使用case语句来显示基于t2.id的Y或N.