如果条件匹配,则SQL返回true

时间:2010-07-13 09:39:07

标签: sql-server tsql

我的数据库中有一个assignment表。我还有一个assignment_notes表,它引用了assignment表。此表中可能存在多行。

当我选择所有作业时,我想检查此作业是否存在一些注释。而我想要的只是一个真/假的回报。

是否可以执行类似(伪)的操作:

  

选择所有作业;如果分配   具有assignment_notes HasNotes = true;其他   HasNotes = false。

我希望我说得足够清楚 - 我不太擅长解释编程内容; - )

5 个答案:

答案 0 :(得分:1)

没有准备好测试SQL Server,但这样的查询应该有效:

SELECT A.*, 
  CAST(
    CASE (SELECT TOP 1 AssignmentNotes_ID 
          FROM AssignmentNotes AN 
          WHERE AN.AssignmentID = A.AssignmentID)
      WHEN NULL THEN 0 ELSE 1 END
    AS BIT) AS HasNotes
FROM Assignments A

答案 1 :(得分:1)

DECLARE @Assignments TABLE
(
    Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    Name VARCHAR(30) NOT NULL
)

DECLARE @AssignmentNotes TABLE
(
    Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    AssignmentId INT NOT NULL,
    Note VARCHAR(MAX)
)

INSERT INTO @Assignments(Name) VALUES('Biology')
INSERT INTO @Assignments(Name) VALUES('Chemistry')

INSERT INTO @AssignmentNotes (AssignmentId, Note) VALUES(1, 'Studies on DNA')
INSERT INTO @AssignmentNotes (AssignmentId, Note) VALUES(1, 'Evolution notes from Darwin')

SELECT
    A.*,
    CASE WHEN COUNT(AN.Id) > 0 THEN 1 ELSE 0 END AS HasNotes    
FROM    
    @Assignments AS A
    LEFT JOIN
    @AssignmentNotes AS AN
    ON A.Id = AN.AssignmentId
GROUP BY
    A.Id,
    A.Name

答案 2 :(得分:1)

SELECT a.*, 
    (SELECT COUNT(*) 
     FROM assignment_notes an 
     WHERE an.assignmentid = a.id) as NumNotes
FROM Assignment a

这将为您提供该作业的音符数量。

答案 3 :(得分:0)

如果使用case语句,则可以将伪代码转换为SQL。在MSDN上:http://msdn.microsoft.com/en-us/library/ms181765.aspx

另一篇文章以及案例:http://www.devx.com/tips/Tip/15633

答案 4 :(得分:0)

这种方法意味着由于返回大量的Assignment字段,您不需要庞大的GROUP BY语句。

SELECT Assignment.*, 
CAST(CASE WHEN NotesQty>0 THEN 1 ELSE 0 END as bit) AS HasNotes
FROM Assignment
LEFT JOIN
(SELECT AssignmentId,COUNT(*) AS NotesQty 
 FROM assignment_notes
 GROUP BY AssignmentId) as Assignment_NotesQty
ON Assignment_NotesQty.AssignmentId=Assignment.AssignmentId