我有两张桌子
BOOK(book_id, book_name)
和
COPY(copy_id, book_id, available(bool))
我希望有一个查询来显示所有副本的book_id,book_name和COUNT(*),这些副本在COPY表中具有相同的book_id,且可用设置为true。示例查询输出应如下所示:
1, BookA, 2
2, BookB, 4
3, BookC, 0
所以BookA有两个COPY元组,可用设置为true。这是我到目前为止所做的,它不起作用。
SELECT * FROM
(SELECT * FROM BOOK)book,
(SELECT book_id, COUNT(copy_id) FROM COPY)copy
WHERE book.book_id = copy.book_id;
答案 0 :(得分:2)
由于MySQL中的1
bool值为true
,因此可以将它们相加
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
答案 1 :(得分: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
这样效率更高一点,因为连接不包含任何具有不可用书籍的行,因此它是一个较小的中间表来处理。