2013-05-14 30 views
0

我有2個表格:作者和書籍。SQL查詢使用2個表中的數據

在作者中,我擁有屬性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); 

任何幫助,將不勝感激

回答

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 
+0

如果兩位作者共用同一個名字,這將返回不正確的結果。 – 2013-05-14 07:48:03

+0

@MartinSmith你說得對,我的不好。糾正。 – 2013-05-14 07:49:25

0

我試圖執行一個查詢,其中給出的作者姓名,對該作者的所有書籍進行計數。

嘗試

select count(1) 
from books b 
inner join authors a on a.AuthorID=b.AuthorID 
where a.AuthorName='Mark Twain' 
+0

很酷的工作。多謝兄弟。我絕對需要觸及一些SQL。 – 2013-05-14 08:59:52

+0

@ryanlawrence請認爲它是你** [答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)**如果它幫助你。 – Luv 2013-05-14 09:49:13

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')