【问题标题】:MYSQL Counting duplicate ID's WHERE booleans are false as TOTAL column, not counting total = 0MYSQL 计算重复 ID 的 WHERE 布尔值作为 TOTAL 列是假的,不计算总计 = 0
【发布时间】:2024-05-20 22:25:02
【问题描述】:

我正在为图书馆系统创建一个数据库,其中每本书的副本都有一个唯一的 ID。 在尝试创建视图时,列出每个标题以及该标题的可用(未归档或已借阅)书籍的总量,我面临的问题是它不会列出没有可用书籍的标题。 决定书是借用还是存档的列作为布尔值,如果其中一个为真,视图将不计算它们。

如果所有副本都不可用,我希望它显示金额为 0。

我已经尝试了多种不同的方法来为此创建视图,但最终还是遇到了相同的问题,或者由于其复杂性而让我忘记了我正在做什么的视图。

CREATE VIEW `visitorbookview` AS
SELECT 
    bo.id,
    bo.title,
    bo.writer,
    bo.description,
    ca.name AS category,
    pu.name AS publisher,
    bo.dewey,
    bo.ebook,
    COUNT(0) AS amount
FROM
    `booknumber` `bn`
    JOIN `books` `bo` ON `bn`.`books_id` = `bo`.`id`
    JOIN `publisher` `pu` ON `pu`.`id` = `bo`.`publisher_idpublisher`
    JOIN `category` `ca` ON `ca`.`id` = `bo`.`category_idcategory`
WHERE
    ((`bn`.`borrowed` = 0)
        AND (`bn`.`archived` = 0))
GROUP BY `bn`.`books_id`

创造

id title writer description category publisher dewey ebook amount
1 Kalle och C Roald Dahl - Barn Rabén Sjögren 800 no 1
2 Harry Potte J.K Rowling - Ungdom Bloomsbury Publ 800 no 10

问题是,如果我将第 1 本书的最后一个副本标记为已存档/已借阅,则它不会再显示在视图中。我明白为什么会这样,我只是不知道如何解决这个问题。

第 5 行更改为已归档 = 1

id books_id borrowed archived comment
1 1 1 0 Empty
2 1 0 1 Broken
3 1 1 0 Empty
4 1 1 0 Empty
5 1 0 1 TEST
6 2 0 0 Empty
7 2 0 0 Empty
8 2 0 0 Empty
9 2 0 0 Empty
10 2 0 0 Empty
11 2 0 0 Empty
12 2 0 0 Empty
13 2 0 0 Empty
14 2 0 0 Empty
15 2 0 0 Empty
NULL NULL NULL NULL NULL

产生以下结果

id title writer description category publisher dewey ebook amount
2 Harry Potter and the Philosophers stone J.K Rowling - Ungdom Bloomsbury Publishing Ltd. 800 no 10

【问题讨论】:

  • 请不要将您的数据发布为图像,而是将其复制到问题正文中。

标签: mysql sql database


【解决方案1】:

你想要一个LEFT JOIN

SELECT bo.id, bo.title, bo.writer, bo.description,
       ca.name AS category, pu.name AS publisher,
       bo.dewey, bo.ebook,
       COUNT(bn.bookid) AS amount
FROM books bo LEFT JOIN
     booknumber bn
     ON bn.books_id = bo.id AND
        bn.borrowed = 0 AND
        bn.archived = 0 LEFT JOIN
     publisher pu
     ON pu.id = bo.publisher_idpublisher LEFT JOIN
     category ca
     ON ca.id = bo.category_idcategory
GROUP BY bo.id, bo.title, bo.writer, bo.description,
         ca.name, pu.name,
         bo.dewey, bo.ebook;

注意事项:

  • FROM 子句中的括号是不必要的,只会使查询更难阅读。
  • 您将所有标识符都放在反引号中。这只会使查询更难编写和阅读。
  • 列引用的默认名称是列名,因此bo.title as title 是多余的。
  • WHERE 子句中的条件需要在ON 子句中,因为LEFT JOIN

【讨论】:

  • 是的,对过度使用反引号感到抱歉,当我查看我的创建语句时,mysql 工作台生成了它们。所有别名和括号都是一样的。我尝试了您的解决方案,但它并没有给我正确的输出。它显示数量为 1 的书 1
  • @JohnRotkins 。 . .您需要从其他一张表中计算一些东西。我修好了。
最近更新 更多