我正在研究SQL Server 2008数据库。该数据库有两个表。
Book
ID
BookCategoryID
Name
IsFlagged
BookCategory
ID
Name
IsFlagged
我需要更新BookCategory表,以便在标记类别中的任何书籍时,BookCategory记录上的IsFlagged属性设置为true。否则,如果类别中没有任何标记的书籍,我需要将BookCategory记录中的IsFlagged属性设置为false。有没有办法做到这一点?我似乎无法弄明白。我正在尝试类似下面的事情,但一直处于死胡同。
UPDATE
BookCategory
SET
IsFlagged = (SELECT COUNT(*) FROM Book WHERE [IsFlagged]=1 AND [BookCategory]=?)
答案 0 :(得分:8)
UPDATE bc
SET IsFlagged = CASE WHEN b.ID IS NULL THEN 0 ELSE 1 END
FROM
BookCategory bc LEFT JOIN
Book b ON b.BookCategoryID = bc.ID AND b.IsFlagged = 1
答案 1 :(得分:3)
UPDATE BookCategory
SET IsFlagged = 0
UPDATE BookCategory b
SET IsFlagged = 1
WHERE EXISTS (SELECT 1 FROM Books
WHERE bookCategoryid = b.id
AND isFlagged = 1)