小编典典

如果其他参数为null,则SQL正确的联接方式

sql

我有此代码及其临时表,因此您可以运行它。

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

create table #quiz
(
    id int identity(1,1),
    quiz_name varchar(50)
)

create table #quiz_details
(
    id int identity(1,1),
    quiz_id int,
    student_id int
)

insert into #student(firstname, lastname)
values ('LeBron', 'James'), ('Stephen', 'Curry')

insert into #quiz(quiz_name)
values('NBA 50 Greatest Player Quiz'), ('NBA Top 10 3 point shooters')

insert into #quiz_details(quiz_id, student_id)
values (1, 2), (2, 1)


drop table #student
drop table #quiz
drop table #quiz_details

因此,您可以看到勒布朗·詹姆斯(Lebron James)参加了NBA前10名3分射手测验,而斯蒂芬·库里(Stephen Curry)则获得了NBA
50名最佳球员测验。

我只想得到他们还没有拿到的东西,例如勒布朗还没有参加过50个最伟大的玩家测验,所以我想要的就是这样。

id   quiz_name                    firstname  lastname
----------------------------------------------------
1    NBA 50 Greatest Player Quiz  NULL       NULL

我需要2个参数,即lebron的ID和测验的ID,以便我知道lebron或stephen尚未接受它,但是如果的值student_id仍然为空,我将如何做呢?

我的尝试:

select
    QD.id,
    Q.quiz_name,
    S.firstname,
    S.lastname
from 
    #quiz_details QD
inner join 
    #quiz Q on Q.id = QD.quiz_id
inner join 
    #student S on S.id = QD.student_id

阅读 211

收藏
2021-04-15

共1个答案

小编典典

这应该使您开始:

-- filter out the student and quiz you want
DECLARE @qid INT = 1
DECLARE @sid INT = 1

SELECT * 
FROM #student AS s
INNER JOIN #quiz AS q  -- you want the quiz
 ON 1=1
LEFT OUTER JOIN #quiz_details AS qd  -- left join here to get result where rows not found
 ON qd.id = q.id 
 AND qd.student_id=s.id
WHERE s.id = @sid
 AND q.id = @qid
 AND qd.id IS NULL -- only return quizes not taken
2021-04-15