回答

收藏

若其它参数为null,则SQL正确的连接方式

技术问答 技术问答 501 人阅读 | 0 人回复 | 2023-09-14

我有这个代码及其临时表,所以你可以操作它。4 }: h* `; H% ?  Q- J
create table #student(    id int identity    firstname varchar   lastname varchar(50))create table #quiz(    id int identity    quiz_name varchar(50))create table #quiz_details(    id int identity    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)drop table #studentdrop table #quizdrop table #quiz_details所以你可以看到勒布朗·詹姆斯(Lebron James)参加了NBA斯蒂芬·库里(Stephen Curry)则获得了NBA0 A4 N) C+ ]( U! g- J% s) f
测试50名最佳球员。
( z0 `# S- f& X, n6 f9 ^我只想得到他们还没有得到的东西,比如勒布朗还没有参加过50个最伟大的球员,所以我想要的就是这样。
% ^/ N0 t$ D( v" j. ?# L% iid   quiz_name                    firstname  lastname----------------------------------------------------1    NBA 50 Greatest Player Quiz  NULL       NULL我需要两个参数,即lebron的ID和测验的ID,以便我知道lebron或stephen它还没有被接受,但如果值student_id还是空的,我该怎么办?6 R  @4 H- R2 w) q' P, X
我的尝试:7 _& h: R8 m% Z* p0 ?# M
select    QD.id,   Q.quiz_name,   S.firstname,   S.lastnamefrom     #quiz_details QDinner join     #quiz Q on Q.id = QD.quiz_idinner join     #student S on S.id = QD.student_id               
, v- G. r' x8 a    解决方案:                                                               
/ |9 G' J) h: ^: k7 K0 j                                                                这应该让你开始:
5 K* {$ s7 b, ]$ |: k-- filter out the student and quiz you wantDECLARE @qid INT = 1DECLARE @sid INT = 1SELECT * FROM #student AS sINNER JOIN #quiz AS q  -- you want the quiz ON 1=1LEFT 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.idWHERE s.id = @sid AND q.id = @qid AND qd.id IS NULL -- only return quizes not taken
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则