SQL:哪个人参加了哪个考试

时间:2018-02-02 12:45:30

标签: sql sql-server

我想要参加或不参加的人和考试 我出于某种原因无法弄清楚

 EXAM:        ID, NAME,      ...etc
 PERSON:      ID, NAME,      ...etc
 PERSON_EXAM: ID, PERSON_ID, EXAM_ID, ...etc

期望的结果

PERSON_ID    EXAM_ID     PERSON_EXAM_ID
1            1           1
1            2           NULL                  
1            3           2
2            1           NULL
2            2           NULL
2            3           3

目前我这样做了

  select 
     p.ID as PERSON_ID, 
     e.ID as EXAM_ID,
     (select pe.ID from PERSON_EXAM pe 
      where pe.PERSON_ID = p.ID and pe.EXAM_ID = e.ID) as PERSON_EXAM_ID
  from PERSON p, EXAM e

但我担心会慢一点 我尝试用一​​个表加入两个表,但由于某种原因我不能这样做

    select p.ID as PERSON_ID, e.ID as EXAM_ID, pe.ID as PERSON_EXAM_ID
    from PERSON p, EXAM e 
    left join PERSON_EXAM pe on 
       p.ID = pe.PERSON_ID and // 'p' isn't recognized because the join is on 'e'
       e.ID = pe.ITEM_ID

1 个答案:

答案 0 :(得分:1)

你有正确的想法。只需使用正确的语法。 从不FROM子句中使用逗号。 始终使用正确的JOIN语法:

select p.ID as PERSON_ID, e.ID as EXAM_ID, pe.ID as PERSON_EXAM_ID
from PERSON p cross join
     EXAM e left join
     PERSON_EXAM pe 
     on p.ID = pe.PERSON_ID and 
        e.ID = pe.ITEM_ID;

古老逗号的语义意味着后续on子句中无法识别表别名。