SQL correct way of joining if the other parameter is null

后端 未结 5 1422
离开以前
离开以前 2021-02-02 06:07

I have this code and its temporary tables so you can run it.

create table #student
(
    id int identity(1,1),
    firstname varchar(50),
    lastname varchar(50         


        
5条回答
  •  失恋的感觉
    2021-02-02 06:44

    My take on it - similar to Patrick's answer with a cross join.

    Full sample available at sqlfiddle

    select
      Q.Quiz_Name Quiz
     ,S.LastName Last
     ,S.FirstName First
     ,QD.Quiz_ID
     ,QD.Student_ID
    from 
    /* Get a full list of ALL Test/Student combinations */
               quiz Q 
    CROSS JOIN student S 
    /* Join the taken tests to the combinations */
     LEFT JOIN quiz_details QD on Q.id = QD.quiz_id
                              and S.id = QD.student_id
    /* Only select where no Quiz_ID exists */
    WHERE QD.Quiz_ID IS NULL
    ORDER BY Q.Quiz_Name, S.Lastname, S.FirstName;
    

提交回复
热议问题