如何检查表是否在另一个表中具有匹配的记录?

时间:2014-02-17 05:46:14

标签: sql database sql-server-2008-r2

我有以下表格:

表1:AccessMenu

userid  item

1        a 

2        b    

2        c

表2:ActionRights

idAdmin   itemCol

2          v

2          m

2          d

期望的结果:

  userid      yes/no

   1           no

   2           yes

当我在userid中将idadminActionRight匹配时,应该Yes返回No

我在下面尝试了查询:

select AccessMenu.userid,
case when ActionRights.IdAdmin=AccessMenu.userid then 'Yes' else 'No' end as 'GRP'
from AccessMenu left join ActionRights
on ActionRights.IdAdmin =AccessMenu.userid

但是通过这个查询,我得到了重复的结果:

 userid      yes/no

   1           no

   2           yes

   2           yes

   2           yes

   2           yes

   2           yes

请帮帮我。

4 个答案:

答案 0 :(得分:1)

SELECT userid, 
       CASE 
         WHEN idadmin IS NULL THEN 'No' 
         ELSE 'Yes' 
       END AS 'Grp' 
FROM   (SELECT accessmenu.userid    AS UserId, 
               actionrights.idadmin AS IdAdmin 
        FROM   accessmenu 
               LEFT JOIN actionrights 
                      ON actionrights.idadmin = accessmenu.userid)z 

答案 1 :(得分:1)

请使用子查询检查:

select distinct
    userid, 
    case when (SELECT COUNT(*) from ActionRights b where b.idAdmin=a.userid)>0 then 'Yes' else 'No' end [Yes/No]
from AccessMenu a

答案 2 :(得分:1)

试试这个

SELECT distinct  UserId, CASE WHEN  IsAdmin  IS  NULL  THEN  'No'  ELSE  'Yes' END AS 'Grp'
FROM (  
      select AccessMenu.userid as UserId ,ActionRights.IsAdmin as IsAdmin
      from AccessMenu left join ActionRights
      on ActionRights.IsAdmin =AccessMenu.userid
     )a

看看

http://www.sqlfiddle.com/#!2/07d52/10

答案 3 :(得分:1)

  

简单。不需要内部查询或子查询。就拿吧   不同

 SELECT DISTINCT AM.USERID,
 CASE WHEN AR.USERID IS NULL THEN 'NO' ELSE 'YES' END AS [YES/NO] 
 FROM #ACCESSMENU AM
 LEFT JOIN #ACCESSRIGHT AR ON AM.USERID=AR.USERID