标记是否存在 JOIN - SQL

Flag if there is a JOIN - SQL

具有相同字段名称的两个 table >> student.id 在学生 table (a) 和 student.id 在记录 table (b)

如果来自学生 table 的 student.id 也在记录 table 中(加入 a.student.id = b.student.id)然后说“是" else "No" as "match"

如果没有重复,那么你可以使用 left join:

select s.*, (case when r.student_id is null then 'No' else 'Yes' end)
from students s left join
     records r
     on r.student_id = s.id;

如果可以重复,则在加入之前删除重复的:

select s.*, (case when r.student_id is null then 'No' else 'Yes' end)
from students s left join
     (select distinct r.student_id
      from records r
     ) r
     on r.student_id = s.id;

考虑一个 LEFT JOIN,它将显示第一个 table 中的所有记录,以及第二个 table 中的所有匹配记录。您可以使用 CASE 语句来显示它们是否匹配。

SELECT
    A.StudentID,
    B.StudentID,
    CASE WHEN b.StudentID IS NOT NULL THEN 'Yes' ELSE 'NO' END As Match
FROM
    StudentA a
    LEFT JOIN StudentB b on a.StudentID = b.StudentID

你可以使用左连接和 case when

select  case when b.student_id is null then 'No' else 'Yes' END match
from  student a
left join  record  b on a.student_id = b.student_id

以下内容不会重复,如果有很多重复,可能会更快。

select *, 
case when exists (select null from other_students b 
                  where b.id = a.id) then 'Yes' else 'No' end student_match
from students a

在此处查看 SQL Fiddle 的实际操作。