1

我有两张桌子

BOOK(book_id, book_name)

COPY(copy_id, book_id, available(bool))

我想要一个查询来显示 COPY 表中具有相同 book_id 且可用设置为 true 的所有副本的 book_id、book_name 和 COUNT(*)。示例查询输出应如下所示:

1, BookA, 2
2, BookB, 4
3, BookC, 0

所以 BookA 有两个可用设置为 true 的 COPY 元组。这是我目前所拥有的,它不起作用。

SELECT * FROM
(SELECT * FROM BOOK)book,
(SELECT book_id, COUNT(copy_id) FROM COPY)copy
WHERE book.book_id = copy.book_id;
4

2 回答 2

2

Since bool values are 1 if true in MySQL, you can sum them up

SELECT b.book_id, 
       b.book_name, 
       sum(c.available) as copy_count
FROM book b
left outer join copy c on c.book_id = b.book_id
group by b.book_id

SQLFiddle demo

于 2012-12-01T10:03:39.853 回答
0

这是另一个变体:

SELECT b.book_id, 
       b.book_name, 
       count(c.available) as copy_count
FROM book b
left outer join copy c on c.book_id = b.book_id and c.available = 1
group by b.book_id

这更有效一点,因为连接不包括任何书籍不可用的行,所以它是一个较小的中间表来处理。

于 2012-12-01T10:32:12.740 回答