我有一个用于库数据库的多个表,我想要计算已经向某个组提供了多少个出版物。
我有这些表
顾客表
CREATE TABLE `patrons` (
`id` int(10) UNSIGNED NOT NULL,
`category_id` int(10) UNSIGNED NOT NULL,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
赞助人类别
CREATE TABLE `patron_categories` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) NOT NULL,
`overdue` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
出版物
CREATE TABLE `publication` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) NOT NULL,
`year` year(4) NOT NULL,
`ISBN` varchar(255) NOT NULL,
`type` varchar(24) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
结帐
CREATE TABLE `checkouts` (
`id` int(10) UNSIGNED NOT NULL,
`publication_id` int(10) UNSIGNED NOT NULL,
`patron_id` int(10) UNSIGNED NOT NULL,
`checkout` date NOT NULL,
`checkin` date NOT NULL,
`actual_checkin` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
这是我的查询,列出赞助人类别及其总顾客及其结帐的当前出版物数量。
SELECT pc.NAME AS Category,
Count(p.id) AS patrons,
Count(c.id) AS publications
FROM patron_categories AS pc
JOIN patrons AS p
ON pc.id = p.category_id
LEFT JOIN checkouts AS c
ON c.actual_checkin = NULL
LEFT JOIN publication AS pub
ON c.publication_id = pub.id
GROUP BY Category
ORDER BY Category
我不知道出了什么问题,但它给出的出版物数量为0,而有许多出版物借给了那些顾客。 请帮忙。 具有虚拟数据的完整数据库位于here。
答案 0 :(得分:0)
除了检查c.actual_checkin
字段是否为空之外,您的查询看起来很好。尝试将join语句更改为ON c.actual_checkin = NULL
到ON c.actual_checkin IS NULL
答案 1 :(得分:0)
试试这个:
SELECT pc.NAME AS Category,
COUNT(p.id) AS patrons,
COUNT(c.id) AS publications
FROM patron_categories AS pc
JOIN patrons AS p
ON pc.id = p.category_id
LEFT JOIN checkouts AS c
ON c.patron_id = p.id
LEFT JOIN publication AS pub
ON c.publication_id = pub.id
GROUP BY Category
ORDER BY Category
结果: