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

时间:2018-01-10 14:50:33

标签: sql sql-server

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

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还没有采用它,但是如果{{1}的值,我该怎么办?仍然是空的?

我的尝试:

student_id

5 个答案:

答案 0 :(得分:13)

这应该让你开始:

-- 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

答案 1 :(得分:5)

很确定你想要这些东西。这将为您提供测验值,并在没有匹配数据时为学生和quiz_details返回NULL。

select *
from #quiz q
left join #quiz_details qd on q.id = qd.quiz_id
left join #student s on s.id = qd.student_id

答案 2 :(得分:3)

这个

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)

会给你

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

编辑:将代码更改为显式cross join而不是隐式,将其留在此处进行比较

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

答案 3 :(得分:2)

我接受它 - 类似于帕特里克的交叉连接答案。

sqlfiddle

提供完整样本
operator

答案 4 :(得分:0)

{{1}}

这将为每位学生提供他们未参加的测验。