2011-06-08 70 views
0

我用下面的查詢這對於每個類別更新總書不包括到期

UPDATE book_categories C, books P, (SELECT cat_id, book_id, COUNT(*) AS TOTAL_BOOKS FROM book_category GROUP BY cat_id) PC SET C.total_books=PC.TOTAL_BOOKS WHERE PC.cat_id=C.cat_id AND P.book_id=PC.book_id AND P.is_expired=false 

與此查詢是它不跳過過期圖書的問題更新total_books掙扎。我需要知道如何跳過已過期的書籍。

這裏是架構:

Create table books (
    book_id Bigint UNSIGNED NOT NULL AUTO_INCREMENT, 
is_expired Bit(1) NOT NULL DEFAULT false, 
Primary Key (book_id)) ENGINE = InnoDB; 

Create table book_categories (
    cat_id Int UNSIGNED NOT NULL AUTO_INCREMENT, 
    total_books Int UNSIGNED NOT NULL DEFAULT 0, 
Primary Key (cat_id)) ENGINE = InnoDB; 

Create table book_category (
    book_category_id Int UNSIGNED NOT NULL AUTO_INCREMENT, 
    cat_id Int UNSIGNED NOT NULL, 
    book_id Bigint UNSIGNED NOT NULL, 
Primary Key (book_category_id)) ENGINE = InnoDB; 

Alter table book_category add Foreign Key (book_id) references books (book_id) on delete restrict on update restrict; 
Alter table book_category add Foreign Key (cat_id) references book_categories (cat_id) on delete restrict on update restrict; 
+0

我已格式化您的文章的自由。下次請注意這一點; 11個月和32個問題應該足以學習Markdown語法! – 2011-06-08 13:52:48

+0

感謝Tomalak,我添加了空格,但是它們只是出現在第一段中。 – Maximus 2011-06-08 13:57:43

回答

1

內部查詢應該是這樣的:

(SELECT cat_id, book_id, COUNT(*) AS TOTAL_BOOKS 
FROM book_category bc 
JOIN books b 
ON bc.book_id = b.book_id 
WHERE b.is_expired ='false' 
GROUP BY cat_id) 
+0

完美!謝謝 – Maximus 2011-06-08 14:07:17

+0

歡迎光臨! =) – ArtoAle 2011-06-08 14:16:12

+0

有一個問題,如果沒有過期的書籍,內部查詢不會返回任何內容,如果沒有匹配,我如何強制它返回0? – Maximus 2011-06-09 14:32:16