0

我有两张桌子:作者和书籍。

在作者中,我有属性 authorID、authorName 和 authorDOB。
authorID 是此表中的主键。

在 books 表中,我具有 bookISBN、authorID 等属性,
其中 bookISBN 为主,authorID 为外键

我正在尝试在给定作者姓名的情况下执行查询,对该作者的所有书籍进行计数。

这是我得到的:

SET @ID =
AuthorID
FROM authors
WHERE ('Mark Twain' = AuthorName);

SELECT COUNT(*)
FROM books
WHERE (AuthorID = ID);

任何帮助将不胜感激

4

3 回答 3

0

如果您认为自己会更频繁地进行搜索,也可以使用函数。只是一个想法。

go
create function totalbooksbyauthor (@authorname varchar(20) ) returns table
as return

select a.authorid, a.authorname, COUNT(b.bookname) bookcount
from authors a
inner join books b 
on a.authorID = b.authorID
where a.authorname = @authorname
group by a.authorid, a.authorname

go

select * from totalbooksbyauthor ('Mark Twain')
于 2013-05-14T09:43:26.980 回答
0

尝试:

SELECT a.authorId, a.authorName, count(*)
FROM authors a
INNER JOIN books b ON b.AuthorID=a.AuthorID
WHERE ('Mark Twain' = a.AuthorName)
GROUP BY a.authorId, a.authorName
于 2013-05-14T07:43:25.653 回答
0

我正在尝试在给定作者姓名的情况下执行查询,对该作者的所有书籍进行计数。

尝试

select count(1) 
from books b
inner join authors a on a.AuthorID=b.AuthorID
where a.AuthorName='Mark Twain'
于 2013-05-14T07:54:43.017 回答