2010-07-13 60 views
0

我在我的數據庫中有一個assignment表。我也有一個assignment_notes表,其中引用了assignment表。該表中可以存在多行。如果條件匹配,則SQL返回true

當我選擇所有的作業時,我想檢查一下這個作業是否存在一些註釋。我只想要一個真實的/虛假的回報。

是否有可能做這樣的事情(僞):

選擇所有任務;如果賦值 有assign_notes HasNotes = true;否則 HasNotes = false。

我希望我做這個很清楚 - 我不是在解釋編程的東西;-)

+0

對於SQL Server的問題,如果您可以讓人們知道您使用的是哪個版本,那麼它會有所幫助 - 某些語言功能在舊版本中不可用。謝謝:) – Meff 2010-07-13 10:32:17

回答

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 
1

沒有SQL服務器準備測試,但這樣的查詢應該工作:

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

「NULL」不起作用 - 它會一直返回「1」 – janhartmann 2010-07-13 10:36:18

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

這將爲您提供該作業的筆記數量。

0

這種方法意味着您不需要大量的GROUP BY語句,因爲返回大量的Assignment字段。

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 
相關問題