2017-06-27 53 views
0

我有sql查詢,其中傳遞了學生ID'IN'子句。 如果沒有與給定的ID匹配的記錄,它不會返回任何內容。 我想查詢返回類似虛假或不存在等,即使沒有記錄匹配SQL:即使沒有匹配,也要返回一些值

//僞查詢(爲了簡便起見,我限制查詢一個表,實際查詢涉及的其它表。)

Select student_id from STUDENTS WHERE s.student_id in (?,?,?); 
+0

是否有學生表中的許多行或大數據? – Vecchiasignora

回答

1

應用OR is null

Select s.student_id 
from STUDENTS s 
WHERE s.student_id in (?,?,?) 
    or s.student_id is null; 

如果加入,使用左連接:

select s.student_id 
from students s 
left join othertable o 
    on o.something = s.something 
WHERE s.student_id in (?,?,?) 
    or s.student_id is null; 

如果學生是在右邊:

select s.student_id 
from othertable o 
left join students s 
    on o.something = s.something 
    and s.student_id in (?,?,?) -- we put this into the join clause so we don't need the "or is null" 
; 
0
IF EXISTs(Select student_id from STUDENTS WHERE s.student_id in (?,?,?)) 
    BEGIN 
    Select student_id from STUDENTS WHERE s.student_id in (?,?,?) 
END 
    ELSE 
    select 0 
相關問題