我正在努力进行以下查询,以更新每个类别的total_books
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
此查询的问题是它不会跳过过期的书籍。我需要一个如何跳过过期书籍的线索。
这是架构:
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 :(得分: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)