我用下面的查询这对于每个类别更新总书不包括到期
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