SQL查询结果与另一个表相关的null

时间:2015-07-13 13:58:18

标签: sql-server

我有3个表(SQL Server) 表1. ComentListaDef(表示评论)
表2. ListaDefeito(表示DefectList)
表3. RespostaComentListaDef(表示与评论相关的答案)

我需要做一个查询,向我提供“RespostaComentListaDef.IdAutor”没有回答的所有“ComentListaDef.Comentarios”。
我希望看到与“RespostaComentListaDef.IdAutor”相关的所有“ComentListaDef.Comentarios”为null。

我正在尝试执行此查询,但它无效。

“ComentListaDef”表示“评论”,“RespostaComentListaDef”表示“答案”。我正在尝试列出作者ID =的所有评论? (RespostaComentListaDef.IdAutor)没有回答。

SELECT ComentListaDef.Comentarios, COUNT(RespostaComentListaDef.IdAutor) 
FROM ComentListaDef   
INNER JOIN ListaDefeito ON ComentListaDef.IdListaDefeitos = ListaDefeito.Id  
LEFT JOIN RespostaComentListaDef on ComentListaDef.Id = RespostaComentListaDef.IdComentListaDef
WHERE ListaDefeito.IdRevisor = 1075  
AND ComentListaDef.IdListaDefeitos = 36  
AND RespostaComentListaDef.IdAutor = 1072  
GROUP BY ComentListaDef.Comentarios HAVING COUNT(RespostaComentListaDef.IdAutor) = 0

2 个答案:

答案 0 :(得分:0)

如果我理解正确:你想要所有没有答案的评论。

not exists条件应该有效:

select whatever
from Comments c
where not exists (select 1 from answers a where a.CommentId = c.Id
                                             and a.AuthorId = @AuthorId)

答案 1 :(得分:0)

左连接到作者的注释,只返回null的项。 (这在功能上与“不在”相同,但我认为如果你习惯使用连接就更清楚了)

SELECT *
FROM CommentListaDef
LEFT JOIN RespostaComentListaDef on ComentListaDef.Id = RespostaComentListaDef.IdComentListaDef AND RespostaComentListaDef.IdAutor =1072  
WHERE RespostaComentListaDef is null
相关问题