我用下面的查詢這對於每個類別更新總書不包括到期
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;
我已格式化您的文章的自由。下次請注意這一點; 11個月和32個問題應該足以學習Markdown語法! – 2011-06-08 13:52:48
感謝Tomalak,我添加了空格,但是它們只是出現在第一段中。 – Maximus 2011-06-08 13:57:43