Update total books excluding expired
I am struggling with following query which updates total_books for each category
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
The problem with this query is it does not skip expired books. I need a clue how to skip the expired books.
Here is the schema:
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;
the inside query should look like this:
(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)
精彩评论