SQL correct way of joining if the other parameter is null

后端 未结 5 1576
离开以前
离开以前 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:41

    This

    Select Q.id , Q.quiz_name ,S.firstname, S.lastname
    from 
        #quiz Q                -- cross join, returns N*K results, do not use without 
        CROSS JOIN #student S  -- where condition that limits it - SAS solution is nicer!
    where not exists (select 1 from #quiz_details where quiz_id = Q.id and student_id = S.id)
    

    will give you

    id  quiz_name                         firstname     lastname
    1   NBA 50 Greatest Player Quiz       LeBron        James
    2   NBA Top 10 3 point shooters       Stephen       Curry
    

    Edit: changed code to explicit cross join rather then implicit, leaving both in here for comparison

    SELECT #quiz Q, # student S           -- old implicit syntax - comma is easily missed
    

    vs.

    SELECT #quiz Q CROSS JOIN #student S  -- makes it clearer what is wanted
    

提交回复
热议问题